I'm working on a do-dad that can be embedded in a page like a youtube video. The particular effect I want needs jQuery to work.
I want to load jQuery on the condition that something on the page hasn't already added jQuery.
I though of testing
if (typeof($)=='function'){...
but that only works if jQuery is loaded & running by the time the page gets to my script. Since best practices these days is to embed you scripts in the footer, my embed code probably will never see jQuery most of the time anyway.
I thought of doing the test onready
instead of onload
, but the onready
function is inside of jQuery. (I suppose I could use a standalone script? is there a good one?)
Lastly, I though of testing for jQuery after a timeout delay, but this seems inelegant at best and unreliable at worst.
Any thoughts?
You can use window.onload
. This fires after domReady, so jQuery would surely be loaded by this point.
And check for jQuery
, not $
. Sometimes people use jQuery with other libraries and use $
for something different.
However, IMHO, I don't think it's a big deal if jQuery gets loaded twice.
Given your constraints, I see only two options:
Use window.load
event:
(function() {
if (window.addEventListener) {
// Standard
window.addEventListener('load', jQueryCheck, false);
}
else if (window.attachEvent) {
// Microsoft
window.attachEvent('onload', jQueryCheck);
}
function jQueryCheck() {
if (typeof jQuery === "undefined") {
// No one's loaded it; either load it or do without
}
}
})();
window.load
happens very late in the loading cycle, though, after all images are and such loaded.
Use a timeout. The good news is that the timeout can probably be quite short.
(function() {
var counter = 0;
doDetect();
function doDetect() {
if (typeof jQuery !== "undefined") {
// ...jQuery has been loaded
}
else if (++counter < 5) { // 5 or whatever
setTimeout(doDetect, 10);
}
else {
// Time out (and either load it or don't)
}
}
})();
You'll have to tune to decide the best values for the counter and the interval. But if jQuery isn't loaded even on the first or second loop, my guess (untested) is that it isn't going to be loaded...unless someone else is doing what you're doing. :-)
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