jQuery DOM ready handlers

Flatiron School / 11 January 2013

The following is a guest post by Rex Feng and originally appeared on his blog. Rex is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here.

jQuery DOM ready handlers

As you work with JavaScript & jQuery, you will quickly get accustomed to wrapping your JS scripts with a DOM ready check. You generally want to do this, because you don’t want your DOM-manipulating JS to run before the DOM is fully loaded.

The standard jQuery ready function is:

If you’ve seen the jQuery ready shortcut, you can also use this (equivalent to the above):

How does this work? Diving into jQuery source, you can see on line 173 that jQuery checks if what is passed in is a function and applies ready to it:

Also, I want to show how you could wrap your JS code without jQuery. Traditionally, it looks like this:

Note the traditional way using window.onload will happen later than jQuery’s ready event.Code snippets to run your JS upon DOM ready without jQuery are available online.

Finally, if you want to wait for both the DOM and complete page (including all frames, objects and images) to be loaded using jQuery, you can use:

Running JS with jQuery upon DOM ready is simple. Using the jQuery ready shortcut is easy and works well.

jQuery without jQuery is a series that aims to open up the jQuery black box. jQuery is just JavaScript, so you should feel comfortable working at lower levels of abstraction and looking at the jQuery source code written in JavaScript.

Convert a Ruby Hash into valid JSON Previous Post The ``to_s`` and ``to_str`` Methods Next Post