robbanp
 

The Rob blog

I'm the creator and co-founder to ThatsToday. I blog mostly about technology and internet related topics.
Monday, November 30, 2009
Javascript / CSS Lazy Loading

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!

Tags
css, javascript, lazy loading, web
Similar articles
The Rob blog
Javascript / CSS Lazy Loading Hi, I just updated my Lazy Loading script to also handle Style Sheets, so why not publish it to the public? I got the origi...
robertpohl - Twitter Search
Blogged: Javascript / CSS Lazy Loading: http://bit.ly/6tPGR9 #javascript #js #web Blogged: Javascript / CSS Lazy Loading: http://bit.ly/6tPGR9 #javascript #js #web
robertpohl - Twitter Search
Bugfixing JavaScript Lazy Loading scripts. Bugfixing JavaScript Lazy Loading scripts.
ASP.NET Weblogs
Lazy Loading JavaScript Files Using ASP.NET AJAX Script Loader The ASP.NET AJAX Script Loader control will make your life easier. Gone are the days where you have to include a multi-line bloc...
ASP.NET Weblogs
Lazy loading in Entity framework What is lazy loading object? As per Martin Fowler, "An object that doesn't contain all of the data you need but knows how to get...
David Walsh :: PHP, CSS, MooTools, jQuery, and Eve
Poll: Should Browsers Implement Lazy Loading? Lazy loading is the process of delaying the load of a resource until it’s needed.  Image a webpage that’s 2,000 pixe...
Close