jQuery: precedence of the load() and ready() events

At first glance the precedence of the load() and ready() events in jQuery should be really easy to understand. Many developers think that first comes the loading of the page and then the completion of the DOM. This is not the case. In fact, if you try something like this:

$(window).load(function() {

    alert('Load');

});

$(document).ready(function() {

    alert('Ready');

});

This will alert first "Ready" and then "Load", because DOM's completion comes first. If you want to preserve the correct order of both events, you should rewrite the above code as follows:

$(window).load(function() {

    alert('Load');
    
    $(document).ready(function() {

        alert('Ready');

    });

});

This turns out to be very handy when you have to perform some pre-caching and pre-loading of your own jQuery application.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.