Why the event / function "load" is not executed after switching to jQuery 3?

Since I upgraded from jQuery 1.x/ jQuery 2.xto jQuery 3.x, my existing code will no longer execute. Everything works fine, but the event listener loadno longer starts, or just sometimes:

$(function() {
    $(window).on("load", function() {
        // this line will never/occasionally be executed
        console.log("window is loaded!");
    });
});
+4
source share
1 answer

A problem may occur when using / switching to jQuery 3. This is because everything ready statesin the new is jQuery 3now completely asynchron. This means that there will be no order for your code.

- , load ready state. ready , , , load .


jQuery:

, ready state load. ready. .

// $(function() {
    $(window).on("load", function() {
        // this line will now be executed again
        console.log("window is loaded!");
    });
// });

, load ready state, .

// track the loading state by yourself
var windowLoaded = false;
$(window).on("load", function() {
    windowLoaded = true;
});

$(function() {
    function afterLoad() {
        console.log("loaded");
    }

    // decide inside your ready state what to do
    if( !windowLoaded ) {
        $(window).on("load", afterLoad);
    }
    else {
        afterLoad();
    }
});

jQuery:

jQuery-, load. :

(function($, window) {
    $.fn.myPlugin = function() {
        $(window).on("load", start);

        function start() {
            console.log("plugin initialized and window loaded");
        }
    };
})(jQuery, window);

/ ready state, , :

$(function() {
    $("#element").myPlugin();
});

, load , ready state.

(function($, window) {
    // track the loading state beside the plugin initialization
    var windowLoaded = false;
    $(window).on("load", function() {
        windowLoaded = true;
    });

    $.fn.myPlugin = function() {
        // decide inside your plugin how to start
        if( !windowLoaded ) {
            $(window).on("load", start);
        }
        else {
            start();
        }

        function start() {
            console.log("plugin initialized and window loaded");
        }
    };
})(jQuery, window);

:

, jQuery 3, / . , asynchron, , / ...

+5

Source: https://habr.com/ru/post/1649135/


All Articles