_jothq
Last Updated: December 03, 2018
·
54.27K
· 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).

5 Responses
Add your response

4377

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 ·
4383

@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 ·
4385

Now I like it better :)

over 1 year ago ·
30521

For check out the survey web page. https://surveyinfo.squarespace.com/ Close friends if you have any type of kind https://needsurvey.jimdofree.com Select the language of your selection; http://surveytips.wikidot.com/ after that show your satisfaction degree. https://surveyfeedback.ucraft.me Standard expertise of Spanish or english language.

6 months ago ·
30864

This particular food is mostly appropriate for the huge breeds only. https://medium.com/@getwetdogfood you could be questioning just how you can pick the best one for your pet dog.

5 months ago ·