Since I've upgraded from jQuery 1.x
/ jQuery 2.x
to jQuery 3.x
, my existing code will not be executed correctly anymore. Everything works fine, but the load
event listener gets not triggered anymore or just sometimes:
$(function() {
$(window).on("load", function() {
// this line will never/occasionally be executed
console.log("window is loaded!");
});
});
The problem can be occur when using/switching to
jQuery 3
. It's because allready states
in the newjQuery 3
are now fullyasynchron
. This means, that there is no given order for your code to be executed.Because of this, it could happen, that
load
is been triggered before yourready state
has been executed. When yourready
function now finally gets triggered, yourload
listener is too late and will not be executed.jQuery Usage:
To change this behavior, just remove the
ready state
around yourload
event listener initialization. There is no need to encapsulate this with aready
function. You can initialize them without.If you need or want to register both events, you can register the
load
event by yourself and decide inside theready state
what to do next.jQuery Plugins:
Another case would be jQuery plugins, that uses the
load
event too. For example:If a developer/user now wraps the plugin initialization in a
ready state
the problem could happen again, just like explained before:A solution would be to track the
load
event in your plugin on your own, to break out theready state
.Conclusion:
Even when this problem not happens to you, in your tests, you should change those code immediately, when using
jQuery 3
, because other users/different browser can run into this trouble. Others may got the problem, because it isasynchron
, you could never know when/if your code gets executed ...