Is there a way to wait until the jquery library has loaded until we execute other external javascript files, so wait for this to completely load:
<script type="text/javascript" src="jquery-1.7.2.js"></script>
then load other files such as:
<script type="text/javascript" src="campaign_winter_2013/bg_outerwear/js/main.js"></script>
<script type="text/javascript" src="campaign_winter_2013/bg_outerwear/js/mousePosSlide.js"></script>
The problem being I am integrating code in a platform and the jquery library is loaded before my scripts.
You can load jquery library first and then invoke methods defined in your JS files. The following code worked for me.
<body>
function loadJQuery(){
var waitForLoad = function () {
if (typeof jQuery != "undefined") {
console.log("jquery loaded..");
// invoke any methods defined in your JS files to begin execution
} else {
console.log("jquery not loaded..");
window.setTimeout(waitForLoad, 500);
}
};
window.setTimeout(waitForLoad, 500);
}
window.onload = loadJQuery;
</body>
Check this:
https://jsfiddle.net/neohunter/ey2pqt5z/
It will create a fake jQuery object, that allows you to use the onload methods of jquery, and they will be executed as soon as jquery is loaded.
It's not perfect.
// This have to be on <HEAD> preferibly inline
var delayed_jquery = [];
jQuery = function() {
if (typeof arguments[0] == "function") {
jQuery(document).ready(arguments[0]);
} else {
return {
ready: function(fn) {
console.log("registering function");
delayed_jquery.push(fn);
}
}
}
};
$ = jQuery;
var waitForLoad = function() {
if (typeof jQuery.fn != "undefined") {
console.log("jquery loaded!!!");
for (k in delayed_jquery) {
delayed_jquery[k]();
}
} else {
console.log("jquery not loaded..");
window.setTimeout(waitForLoad, 500);
}
};
window.setTimeout(waitForLoad, 500);
// end
// now lets use jQuery (the fake version)
jQuery(document).ready(function() {
alert('Jquery now exists!');
});
jQuery(function() {
alert('Jquery now exists, this is using an alternative call');
})
// And lets load the real jquery after 3 seconds..
window.setTimeout(function() {
var newscript = document.createElement('script');
newscript.type = 'text/javascript';
newscript.async = true;
newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(newscript);
}, 3000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With