jQuery

jQuery $(document).ready vs. $(window).load

At some point or the other, you must have come across  $(document).ready and $(window).load event. At first glance, both of these powerful tools appear to be doing the same job. But did you know the subtle difference between them? Read on to find out the exact difference and how they work.

jQuery $(document).ready vs. $(window).load

Let’s go with the jQuery $(window).load event first.

The window load event executes only after all the elements of the web page are completely loaded. This means that the page has to load the images, css, any inline styling (if applied), iframes, scripts, etc. completely in order for the $(window).load to fire off the associated code. So if it takes 5 seconds to download all of the elements in the webpage, then the $(window).load event will fire off only after 5 seconds. It’s corresponding jQuery code will look like this:

$(window).load(function() {
// This alert below is executed only when complete page is completely loaded, including all images, objects, css, frames, etc.
alert("window is loaded");
});

Now we get to $(document).ready

The document ready method executes when the HTML document is loaded and the DOM is ready, even if all the graphics, scripts, etc. haven’t loaded yet. It’s corresponding jQuery code will look like this:

$(document).ready(function() {
// This alert is triggered when HTML document is loaded and DOM (Document Object Model) is ready
alert("document is ready");
});

So which one is the right choice and when to use it? Well, there’s no wrong answer. In fact, both of them have their own uses. Here’s what I suggest.

1. If you have an element/object that you want to make sure, loads completely in order for an event associated with that element to trigger, then use jQuery $(window).load. So let’s say you have an image that you want to be loaded completely in order to fire off some code, then attach the code to the on load event of this image.

2. If you are not concerned about the elements being loaded and/or want to execute code unconditionally without connecting it to some other element’s presence in the page, then go for jQuery $(document).ready. That way, you can hook up your events for certain elements before the window loads.

Order of execution of jQuery $(document).ready and $(window).load

  • jQuery $(document).ready is excuted first.
  • jQuery $(window).load is executed later, towards the end of the load of the connected element.
Your Turn!

Hope this article was able to shed some light on jQuery $(window).load vs $(document).ready. If you do know of some more reasons, please feel free to share.

Share your thoughts, comment below now!

*

*