i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

Smallest DOMReady code, ever.

update: after an insightful conversation, there are several other intrinsicies involved to get a solid domReady working across multiple browsers. Thus because of this, $script.js has an updated version of how a proper domReady should be implemented thanks to research done by @jdalton.

This evening after tooling around with trying to optimize bits and pieces from a recently formed project ($script.js - async JS loader & dependency manager), I decided to look further into shortening the DOMReady code - since part of the goal is to have the smallest amount of code possible.

So... I tweeted my efforts totaling 87 characters. Eventually a few responses came in. Like changing regex to /oade|ompl/, and then dropping the optional setTimeout 2nd parameter. Then after looking at readyState spec, just going with a completely different regex such as !/in/... then reverse the ternary. Somewhere in the middle I added the second attempt. Note that you don't even need .test()!

Putting it all together

Weighing in at 62 characters. The shortest DOMReady code, ever.

function r(f){/in/(document.readyState)?setTimeout(r,9,f):f()}

Here's a gist.

One final thing, although this was a fun exercise, it should be noted that you'd need a shim to fix Firefox <=3.5. Otherwise this works in Chrome, Safari, Firefox 3.6+, even IE6,7,8,9. Twitter for the win. Cheers.

[UPDATE] It turns out that only IE wasn't able to understand a few things...

So to get this to fully work in every browser again, we have to take into account this issues.

  • IE must have .test() (doesn't get /foo/('foo')
  • IE requires a 2nd arg (Gecko, Webkit does not) (eg: setTimeout(foo)
  • IE's 3rd arg is to specify a language (wow, how stupid is that

So we're back to this.

function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

And of course one final note, nothing will be able to beat the built-in DOM event at 47 characters (although it won't fire after being loaded once).

document.addEventListener('DOMContentLoaded',f)

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @ObviousCorp. Previously @Twitter, @Google, and @Yahoo, author of Strobist® Info co-author of JavaScript Design Patterns, co-creator of the Ender JavaScript Framework, a Photographer, and an amateur Mixologist. This is my website. Welcome!

On this site I write about JavaScript. You can also follow along with my open-source work on Github.

This site is optimized and works best in Microsoft Internet Explorer 6.