I'm writing a little JavaScript tool for myself that I plan on making available to other people and it uses jQuery. My dream for this little utility is for people to be able to include a single .js
file from a remote source and, when that file is loaded, have it check to see if jQuery has already been included and, if it has, make sure it's a recent enough version so as to be compatible with what my code needs to do. Some pseudocode which may explain my issue more clearly (this code would appear at the top of the single .js
file I mentioned earlier):
if jQuery is loaded {
if version is less than (say) 1.3 {
// load latest version of jQuery
}
} else {
// load latest version of jQuery
}
// and do the jQuery.noConflict()
// dance to avoid trampling any other libraries, etc. that the
// user may be utilizing.
// The rest of my code lives here, happy in the knowledge that it's running in
// isolation from the rest of the JS that the page knows about.
My question, distilled into three friendly parts:
The overarching idea here is that any old user could grab a small snippet of HTML and drop it into their site/blog/whatever and have it Just Work™. And since many modern publishing platforms now ship with jQuery, I can't just quietly assume that it's not running and include it.
Thanks for your time, and please let me know if any part of this isn't clear or if I can provide additional context/detail to make your providing a response easier.
function doMyStuff(jQueryJustForThisFn) {
// do jQuery stuff!
jQueryJustForThisFn('div').addClass('wow');
}
function check() {
return window.jQuery && jQuery.fn && /^1\.[3-9]/.test(jQuery.fn.jquery);
}
if ( check() ) {
doMyStuff( jQuery );
} else {
var script = document.createElement('script'),
timer = setInterval(function(){
if ( check() ) {
clearInterval(timer);
document.body.removeChild(script);
doMyStuff( jQuery.noConflict(true) );
}
}, 30);
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js';
document.body.insertBefore( script, document.body.firstChild );
}
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