Hi, I just updated my Lazy Loading script to also handle Style Sheets, so why not publish it to the public? I got the original script (written by: Bob Matsuoka) a while back from this Ajaxian article. It did not work 100% for my needs so I did some changes:
First I created a callback function so that it adds the loaded script only after it's done (i.e. the callback)
Then I added support for lazy loading of stylesheet files.
How to use it:
var file = "myscript.js";
var callback = function(){
alert("Done loading "+file);
};
LazyLoader.load(file, callback);
The code:
var LazyLoader = {}; //namespace
LazyLoader.timer = {}; // contains timers for scripts
LazyLoader.scripts = []; // contains called script references
LazyLoader.load = function(url, callback) {
// handle object or path
var classname = null;
var properties = null;
var executeCallback = function() {
LazyLoader.scripts.push(url);
callback();
};
// try {
// make sure we only load once
if ($A(LazyLoader.scripts).indexOf(url) == -1) {
// note that we loaded already
var script;
if (url.indexOf('.js') != -1) {
script = document.createElement("script");
script.src = url;
script.type = "text/javascript";
} else if (url.indexOf('.css') != -1) {
script = new Element('link', { rel: 'stylesheet', media: 'screen', type: 'text/css', href: url });
} else {
alert('unsupported lazy loading');
}
$$("head")[0].appendChild(script); // add script tag to head element
// was a callback requested
if (callback) {
// test for onreadystatechange to trigger callback
script.onreadystatechange = function() {
if (script.readyState == 'loaded' || script.readyState == 'complete') {
executeCallback();
}
}
// test for onload to trigger callback
script.onload = function() {
executeCallback();
return;
}
// safari doesn't support either onload or readystate, create a timer
// only way to do this in safari
if (Prototype.Browser.WebKit || Prototype.Browser.Opera) { // sniff
new PeriodicalExecuter(function(pe) {
if (/loaded|complete/.test(document.readyState)) {
pe.stop();
executeCallback(); // call the callback handler
}
}, 1);
}
}
} else {
if (callback) {
executeCallback();
}
}
Please note that you need to reference the prototype.js framework for DOM lookups. The code above can easily be modified to use jQuery or another instead.
Enjoy!