3

I know the basic difference between these states but a weird problem was came in one of our project

jQuery(document).ready(function () {
   console.log('Dom is ready');
   jQuery(document).ready(function () {
       console.log('Inner Dom ready');
   });
});

Result :-

Dom is ready
Inner Dom ready

Now, Thats fine at any time, whenever I call document.ready(), It executes its handler.

But if you look at this

jQuery(window).load(function () {
    console.log('Window Loaded');
    jQuery(window).load(function () {
        console.log('Inner window load');
    });
});

Result :-

Window Loaded

Why the inner window load never executes its handler, even though window is already loaded.

Thanks for your comments and answers but i am just curious to know how they work internally, I agree jQuery(window).load() event only fires once so there is no chance of any other load event handler to execute then why this rule is not applied to jQuery(document).ready(). Does it set some kind of flag or something and checks every time we call it.

Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42
Amit Singh
  • 266
  • 3
  • 13
  • look into this : http://stackoverflow.com/questions/4584373/difference-between-window-load-and-document-ready-functions – Dil85 Sep 28 '16 at 06:52
  • Why on earth would you nest them? I suppose it's because `window.onload` can only be called once, but jQuery wraps the functions up in something, so it can only be called when the window actually has loaded, not later, which is why the inner call doesn't work. While `DOMContentLoaded` and jQuery's `ready` will be called whenever, as long as the document has loaded. – adeneo Sep 28 '16 at 06:53

1 Answers1

5

$(document).ready() executes when HTML-Document is loaded and DOM is ready. so inner ready() invokes because DOM is already become ready. ready() checks only current state not compare with previous state. so condition something like this

if state=="ready" then invoke latest $(document).ready();

This condition is true for all level ready() method.

BUT

$(window).load() executes when complete page is fully loaded, including all frames, objects and images. In simple way, load() is executes when state changed to loaded state from another state. First load() executed when state become loaded from another state, but inner load() not detected and state changes so it will not executed.

if (is_state_changed=true AND current_state=="ready" AND current_state !== previous_state) then invoke latest $(window).load();

Above condition is true for first/outer load(), but not true for inner load() because state is not changed(its remain same) for inner load()

Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42