If you've done any significant Javascript development, I'm sure that you've run into the need to dynamically include an external javascript library. There are many existing libraries that will do this for you quite easily. But what if you are not able to take advantage of such a library? What if that library is precisely the javascript you wish to dynamically load?
Hmm. In that case you can use the following code snippet to bootstrap the process.
function loadScript(src, callback) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var loaded = false;
script.setAttribute('src', src);
script.onload = script.onreadystatechange = function() {
if (!loaded && (!this.readyState || this.readyState == 'complete'
|| this.readyState == 'loaded') ) {
loaded = true;
callback();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
}
head.appendChild(script);
}
For example, here's how I used it to bootstrap jQuery in a bookmarklet I wrote.
(function() {
function loadScript(src, callback) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var loaded = false;
script.setAttribute('src', src);
script.onload = script.onreadystatechange = function() {
if (!loaded && (!this.readyState || this.readyState == 'complete'
|| this.readyState == 'loaded') ) {
loaded = true;
callback();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
}
head.appendChild(script);
}
function withJQuery(cb) {
loadScript('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js',
function() {
cb(jQuery.noConflict(true));
}
);
}
withJQuery(function($) {
// do something with jQuery
});
})();
Notice that the above code adds nothing to the global namespace. The code is localized within an anonymous function and jQuery.noConflict(true) is called so that jQuery cleans up after itself and resets the $ and jQuery globals to whatever they were prior to the script being loaded. Nice, but admittedly a lot of bootstrap code.
I've been thinking a lot lately about how a robust javascript packaging system would look. But even then, a nice library wouldn't help a lot here. It would have to be part of the language, and I am not anxious for any additions to the language that have not been very well vetted.
0 comments :: Dynamically load external Javascript in a cross-browser way
Post a Comment