Reputation: 20539
Wordpress loads jQuery automatically. I want to use it, but I get:
jQuery is not defined
This is because various plugins mess with the ordering of scripts. So there's no guarantee that my script will load AFTER jQuery is loaded. So if it loads before, I get that error.
Can I wrap my script in something that waits for jQuery to load, and then executes my script?
Notes
Upvotes: 0
Views: 2422
Reputation: 2232
All functions in window.deferAfterjQueryLoaded
will be runned after jQuery
is defined, so if you push all your inizializations in window.deferAfterjQueryLoaded
you can be sure that they will be runned after jQuery
<script>
if (!window.deferAfterjQueryLoaded) {
window.deferAfterjQueryLoaded = [];
//delete Object.defineProperty; //add this if you want to check the support
if (typeof (Object.defineProperty) === "function") {
Object.defineProperty(window, "jQuery", {
set: function (value) {
window.setTimeout(function () {
$.each(window.deferAfterjQueryLoaded, function (index, fn) {
fn();
});
}, 0);
Object.defineProperty(window, "jQuery", {value: value});
},
configurable: true
});
} else {
nIntervId = window.setInterval(function () {
if (typeof (jQuery) !== "undefined") {
$.each(window.deferAfterjQueryLoaded, function (index, fn) {
fn();
});
clearInterval(nIntervId);
}
}, 10);
}
}
window.deferAfterjQueryLoaded.push(function () {
(function ($) {
console.log("After jquery is loaded");
})(jQuery);
});
</script>
<script>
window.deferAfterjQueryLoaded.push(function () {
(function ($) {
console.log("After jquery is do something else");
})(jQuery);
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You can read more abount Object.defineProperty, you can check the cross browser support here
Upvotes: 2
Reputation: 383
IMHO when 'load' is triggered you can use jQuery:
window.addEventListener('load', (event) => {
// your code
});
Upvotes: 3