Difference between nested $(document).ready() and

2020-07-23 04:45发布

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.

1条回答
老娘就宠你
2楼-- · 2020-07-23 05:32

$(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()

查看更多
登录 后发表回答