Last Updated: March 21, 2023
·
225.4K
· dizpers

jQuery: When to use $(document).ready() and when $(window).load()

Source

http://4loc.wordpress.com/2009/04/28/documentready-vs-windowload/

Summary

jQuery offers two methods to execute code and attach event handlers: $(document).ready and $(window).load.

$(document).ready()

The document ready event fired when the HTML document is loaded and the DOM is ready, even if all the graphics haven’t loaded yet. If you want to hook up your events for certain elements before the window loads, then $(document).ready is the right place.

Code:

$(document).ready(function() {
    // document is loaded and DOM is ready
    alert("document is ready");
});

$(window).load()

The window load event fired a bit later, when the complete page is fully loaded, including all frames, objects and images. Therefore functions which concern images or other page contents should be placed in the load event for the window or the content tag itself.

Code:

$(window).load(function() {
    // page is fully loaded, including all frames, objects and images
    alert("window is loaded");
});

Background

I also want to post some words about my case. If simplify my task it was to get the top position of div below image. You can see this situation here (and codepen link). You should refresh several times - and you will see that with $(document).ready() height of image doesn't matter - because it doesn't loaded, but $(window).load() case shows bigger value (because image is loaded).

4 Responses
Add your response

Could you summarize the article in your tip. I don't see the point of using coderwall to repost links. Then it's just another twitter.

over 1 year ago ·

@markushausammann I added some additional info about this topic.

PS About reposting links in coderwall. Coderwall add special sign if post have only link - it means that they are support this kind of sharing information. :-)

But you are right - some additional info with links may be really helpfull - background for example (usecase of author).

over 1 year ago ·

Now I like it better :)

over 1 year ago ·

Useful and informative

over 1 year ago ·