Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(window).on('load') does not get called correctly inside jQuery(document).ready()

I used to have this code in my JavaScript file, and it used to work...

jQuery(document).ready(function ($) {
    "use strict";

    $(window).load(function (event) {
        LoadPage();
    });

after updating jQuery to version 3.3.1, I had to replace $(window).load with $(window).on('load') as it is deprecated. So this is the new code:

jQuery(document).ready(function ($) {
    "use strict";

    $(window).on('load', function (event) {
        LoadPage();
    });

Problem is this new code, does not behave as expected all the time... in Chrome LoadPage() method is called as expected. If I used MS Edge, it does not hit LoadPage() method at all. If I use Chrome incognito mode, it sometimes hit the method and sometimes doesn't... any idea why this is happening?


2 Answers

OK, I found the answer here: jQuery 3 - Github Issues

This is explanation, by Timmy Willison from jQuery Core Team:

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

The fix is to bind the load outside of ready:

This is how the functions should be called:

$(function() {
  // Things that need to happen when the document is ready
});

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

I got this problem today. As i must trigger third-party code after document.ready on my page but that code already have window.on("load") on it. So i have to monkey-patching jQuery on function like this.

(function safeLoaded($){
    var old = $.fn.on;
    var monkey_on = function(){
        if(this[0] == window && arguments[0] == "load"){
            if (typeof arguments[1] === 'function' && document.readyState === "complete"){
                arguments[1].call(this);
                return this;
            }
        }
        return old.apply(this, arguments);
    };
    $.fn.on = monkey_on;
})(jQuery);

If document has already loaded, just trigger function directly instead of add event listener for it. Don't know why they don't do this on jQuery.

like image 44
takid1412 Avatar answered Jul 29 '26 08:07

takid1412