Dynamically load the jQuery library
I’ve been working on a little web page widget for loading related conversations from gravity.com. My goal was to require only a single script tag with a few attributes and that’s it. However my code has a dependency on some fanciness in jQuery. At some point it will make sense to write it all out in javascript, but right now I’d like to use jQuery.
So I need to remote load the jQuery library if it doesn’t already exist in this current page. I looked around and found a few solutions, but I wanted a simple function that I could pass a callback to that ensured my code would execute or fail silently. So I put together this function:
var ensureJQuery = function(callback) {
// set our vars
this.callback = callback;
this.interval = 50;
this.max_time = 5000; // 5 seconds
this.elapsed = 0;
this.jquery_url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
// if jQuery is loaded, run it
if (typeof jQuery == 'function') {
return this.callback(jQuery);
}
// insert jquery load script tag
var script = document.createElement('script')
script.setAttribute('type','text/javascript')
script.setAttribute('src',this.jquery_url)
if (typeof script != 'undefined') {
document.getElementsByTagName('head')[0].appendChild(script);
}
// interval our check and run callback when jQuery loaded
this.jquery_check = setInterval(function() {
this.elapsed += this.interval;
if (typeof jQuery == 'function') {
clearInterval(this.jquery_check);
return this.callback(jQuery);
}
if (this.elapsed > this.max_time) {
clearInterval(this.jquery_check);
return false;
}
},this.interval);
}
It’s not very complicated. It checks if jQuery is a function in the current environment. If not it creates a script tag to load it. Then it waits until it’s loaded and executes the callback. It passes jQuery into the callback so you can set it to $ and know that you won’t have any conflicts.
Here’s a basic usage:
ensureJQuery(function($) {
alert('jQuery version '+$.prototype.jquery+' is loaded!');
});
It’s a pretty simple load and works nicely for my application.
You can download the latest version of this code at: http://github.com/jasonmoo/jQuery-dynamic-loader





