Writing your own DOM ready listener

Today I asked a question on StackOverflow on how to attach a function to the browser’s DOM ready event, in a cross-browser way, but without exporting any globals (keeping everything in an anonymous function’s closure) and without including any external file. As a result, with some help of a friendly StackOverflow user, I put together a code snippet that:

  • takes a single function as argument,
  • attaches that function to the DOM ready event in all browsers supported by jQuery,
  • is idempotent (will never fire the given function twice),
  • does not export any globals,
  • compiles down to less than 590 bytes (less than 300 bytes gzipped),
  • is based on the jQuery source code (I take no credit for it).

I take no credit for writing this script. If you want to use it, please include jQuery’s license comment.

Update

Here is a CoffeeScript version: