window load inside a document ready? window load inside a document ready? jquery jquery

window load inside a document ready?


This works fine and is an acceptable practice. After all, as you describe, there may be cases where the logic in the $(window).load() handler depends on work taking place after the DOM is ready. If the window is in fact already loaded by the time you set up $(window).load(), the handler will just fire immediately.


EDIT:

NOTE: This answer is only applicable to jQuery v2 and below.


jQuery .ready() event:

The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.

jQuery .load() event method:

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

Based on the jQuery documentation above, I've seen nothing that would indicate any issues with the following:

$(document).ready(function () {    // will fire IMMEDIATELY after the DOM is constructed    $(window).load(function() {        // will only fire AFTER all pages assets have loaded    })});

Placing a .load inside of a ready simply guarantees that the DOM is ready whenever the load is fired.

One may wish to place all jQuery code within a single DOM ready handler, and yet still may have a sub-set of jQuery code that requires all images be loaded first. This arrangement guarantees that all code be triggered once on DOM ready and the rest will be triggered subsequently whenever the page assets have finished loading.

This may ultimately be more of an issue of personal preference, however the OP was clearly asking if this arrangement would cause problems. This has not proven to be true.


I ran into this problem recently... from jQuery version 3, we can no longer put $(window).on('load') inside document.ready()... because ready handler are called asynchronously, which means ready can be called after load.

From jQuery Core Team: Github: jQuery 3 issues

To be clear, we understand what's causing this. We recently made readyhandlers fire asynchronously. This has advantages that are hard togive up. The disadvantage is that the ready handler can sometimes fireafter the load event if the load event fires quickly enough. The sideeffect you're seeing in this issue is that you're binding a load eventhandler after the load event has already fired.

The fix is to bind the load outside of ready.

$(function() {   // Things that need to happen when the document is ready});$(window).on("load", function() {   // Things that need to happen after full load});