LazyLoad 2.0.0 released

Thursday August 06, 2009 @ 09:42 PM (PDT)

After quite a while without updates, I’ve finally released version 2.0.0 of LazyLoad.

LazyLoad is a tiny (only 1,541 bytes minified), dependency-free JavaScript library that makes it super easy to load external JavaScript and (new in this version) CSS files on demand. It’s ideal for quickly and unobtrusively loading large external scripts and stylesheets either lazily after the rest of the page has finished loading or on demand as needed.

In addition to CSS support, this version of LazyLoad also adds support for parallel loading of multiple resources in browsers that support it. To load multiple resources in parallel, simply pass an array of URLs in a single LazyLoad call.

Downloads

Usage

Using LazyLoad is simple. Just call the appropriate method — css() to load CSS, js() to load JavaScript — and pass in a URL or array of URLs to load. You can also provide a callback function if you’d like to be notified when the resources have finished loading, as well as an argument to pass to the callback and a scope in which to execute the callback.

// Load a single JavaScript file and execute a callback when it finishes loading.
LazyLoad.js('http://example.com/foo.js', function () {
  alert('foo.js has been loaded');
});

// Load multiple JS files and execute a callback when they've all finished.
LazyLoad.js(['foo.js', 'bar.js', 'baz.js'], function () {
  alert('all files have been loaded');
});

// Load a CSS file and pass an argument to the callback function.
LazyLoad.css('foo.css', function (arg) {
  alert(arg);
}, 'foo.css has been loaded');

// Load a CSS file and execute the callback in a different scope.
LazyLoad.css('foo.css', function () {
  alert(this.foo); // displays 'bar'
}, null, {foo: 'bar'});

Supported Browsers

  • Firefox 2+
  • Google Chrome (all versions)
  • Internet Explorer 6+
  • Opera 9+
  • Safari 3+
  • Mobile Safari (all versions)

Other browsers may work, but haven’t been tested. It’s a safe bet that anything based on a recent version of Gecko or WebKit will probably work.

Caveats

All browsers support parallel loading of CSS. However, only Firefox and Opera currently support parallel script loading while preserving execution order. To ensure that scripts are always executed in the correct order, LazyLoad will load all scripts sequentially in browsers other than Firefox and Opera. Hopefully other browsers will improve their parallel script loading behavior soon.

Sadly, Firefox, Safari, and Google Chrome don’t provide any indication when a CSS file has finished loading. In these browsers, CSS load callbacks will execute after a short delay, but there’s no way to automatically guarantee that the CSS has finished loading before the callback is executed. Luckily, there’s a fairly painless manual workaround that you can use to detect when CSS has finished loading, but it’s not possible for LazyLoad to do it for you.

Comments

I assume that the problem is more in knowing that the browser finished to receive the CSS file, and less in the time it takes the browser to actually parse and process it, right?

So in cases where the CSS file is on the same server (which I hope/expect is the common case), and when callback on load is needed, why not use something like XMLHttpRequest to get the content and append it to the page?

The main downside I see is that the page will have the content, instead of a link element referring to the CSS file. But it will allow to know exactly when the loading is finished. I’m not sure it’s a bad tradeoff, at least as an option. For most (though admittedly not all) users the main concern is to get the CSS, not to get a nice link element.

Yep, this would be a reasonable workaround. However, CSS residing on the same server is much less of a common case than you might expect these days, since CDN usage is becoming more and more widespread.

When I considered the tradeoffs involved in adding a bunch of code to LazyLoad to implement workarounds for the CSS loading issue, I decided it just wasn’t worth it. Needing to know exactly when CSS has finished loading is actually not a very common use case (in my experience, at least), and since there are several reasonably simple manual workarounds, I decided it wasn’t worth adding significant weight to LazyLoad.

I may revisit this decision in the future, though.

You’re right. I can see how it’s not worth the investment for you right now. I was mostly wondering if there was also a technical or theoretical problem, and you’re right that usage of CDNs does reduce the utility of this.

Thanks for the response and details.

I assume this still loads the items just once even if it is repeated?

LazyLoad doesn’t do any checking to try to determine whether something has already been loaded. If you tell LazyLoad to load something, LazyLoad will tell the browser to load it.

The previous version of LazyLoad did have a loadOnce() method, but it was suboptimal and I removed it in 2.0. I may implement a replacement in a future version, though.

我想知道,如果CSS文件加载后,什么时候能够渲染页面?

This would be a nice feature to have. I looked at your original loadOnce() method, and while it wasn’t perfect, it didn’t seem “that” bad.

This is a great resource! I’m using it in one of my projects to dynamically load wordlists. It has operated flawlessly. Thank you for your great work.

I know it is not a performance tweak for lazy loading after the page has been loaded but YSlow and Page Speed expect CSS in the head section and JS at the end of the body section.

Is there any chance of appending JS to the body instead of the head?

In this case, YSlow and Page Speed just aren’t smart enough to realize that the JS was loaded lazily. There’s no performance difference between injecting lazy-loaded script nodes into the head vs. the body.

Unfortunately, appending script nodes to the body can cause errors in IE, so LazyLoad appends to the head to be safe.

appendChild breaks Chrome 5, FF 3 and IE 8 if it’s done immediately after readyState == ‘complete’

On each browser the whole document gets replaced.

it was a bit redundant anyway to call LazyLoad.load but it did make good alliteration.

it would be nice to be able to detect if some files failed to load. maybe even a simple catchall method that worked like this:

LazyLoad.setFailHandler(function(failedFile, waitingCallback, obj, scope) {

});

this way the fail handler can call the callback if it wants to or do something else.

Hello,


I’m trying to use your LazyLoad to load jQuery asynchronously to speed up page load. Thanks for the tool.

This works well in IE, where it loads the jQuery framework and events on the page can use the $(myobject) function, but in Firefox, even though it loads the jQuery javascript, the $() does not work! Do you know why this is?

I am using:

(function() {

    LazyLoad.js(‘/Cache/CacheContent?key=StandardJavascript&version=1&type=javascript’,    function () {
     alert(‘The javascript has been loaded’);
  });

})();

Thanks!

can not resolve cache problem, if you call 3 times “LazyLoad.js(‘jq.js’)”,then it will load the js file 3 times

Can you be more specific?

If you expect jq.js to be loaded from the cache and that isn’t happening, then the most likely reason is that the file is being served with incorrect HTTP headers. That’s an issue between the server and the browser that LazyLoad has no control over.

If you expect jq.js to be executed only once even if you load it multiple times, then you may have misunderstood how LazyLoad works. If you call LazyLoad three times with the same JS URL, it will execute that JS three times.

Hello, I’m trying this script to lazyload an advertising js with content inside a div, but instead of loading the js in the div, the code goes to the head. Did I misunderstand the whole thing?

Thanks!

Like all dynamic script loaders, LazyLoad is asynchronous, so document.write calls in a script won’t work the same way they do when a script is included statically. There’s no good solution for this. I recommend avoiding document.write.

This is a problem and it rules out lazyloading advertising (many agency use document.write and we have no control over this).

Thanks anyway for your great work!

First of all, thanks for the nice script.

I’ve changed the load method according to my needs. I always want to load the javascript once. So instead creating a new method ‘loadOnce’ I’ve changed the ‘load’ method. This method will always check if a script is already loaded. If so, it will skip the loading process for these scripts. I will update the script soon with a better solution, like adding a parameter if you require loading once or not. The script works fine for me at the moment. Have fun!

function load(type, urls, callback, obj, scope) {
   
var i, len, node, p, url;

   
// Determine browser type and version.
    getUserAgent
();

   
if (urls) {
       
// Cast urls to an Array.
        urls
= urls.constructor === Array ? urls : [urls];


       
if (type === 'css' || ua.gecko || ua.opera) {
            queue
[type].push({
                urls
: [].concat(urls), // concat ensures copy by value
                callback
: callback,
                obj
: obj,
                scope
: scope
           
});
       
} else {
           
/* Quick & dirty 'loadOnce' check */
           
var tmp = new Array();
           
var scripts = $('head').find('script');
           
for (a = 0, len = urls.length; a < len; a++) {
               
var found = false;
               
for (z = 0, len2 = scripts.length; z < len2; z++) {
                   
if (scripts[z].src.search(urls[a]) != -1) { found = true; break; }
               
}
               
if (!found) { tmp.push(urls[a]); }
           
}

           
// Set the new url array.
            urls
= tmp;
           
if (urls && urls.length > 0) {
               
for (i = 0, len = urls.length; i < len; ++i) {
                    queue
[type].push({
                        urls
: [urls[i]],
                        callback
: i === len - 1 ? callback : null, // callback is only added to the last URL
                        obj
: obj,
                        scope
: scope
                   
});
               
}
           
}
           
else {
               
// There is nothing to load, so call the callback directly.
               
if (callback) { callback(); }
               
return;
           
}
       
}
   
}

   
// If a previous load request of this type is currently in progress, we'll
   
// wait our turn. Otherwise, grab the next item in the queue.
   
if (pending[type] || !(p = pending[type] = queue[type].shift())) {
       
return;
   
}

    head
= head || d.getElementsByTagName('head')[0];
    urls
= p.urls;

   
for (i = 0, len = urls.length; i < len; ++i) {
        url
= urls[i];

       
if (type === 'css') {
            node
= createNode('link', {
                href
: url,
                rel
: 'stylesheet',
                type
: 'text/css'
           
});
       
} else {
            node
= createNode('script', { src: url });
       
}

       
if (ua.ie) {
            node
.onreadystatechange = function () {
               
var readyState = this.readyState;

               
if (readyState === 'loaded' || readyState === 'complete') {
                   
this.onreadystatechange = null;
                    finish
(type);
               
}
           
};
       
} else if (type === 'css' && (ua.gecko || ua.webkit)) {
           
// Gecko and WebKit don't support the onload event on link nodes, so we
           
// just have to finish after a brief delay and hope for the best.
            setTimeout
(function () { finish(type); }, 50 * len);
       
} else {
            node
.onload = node.onerror = function () { finish(type); };
       
}

        head
.appendChild(node);
   
}
}

Hi,
I need to increase the performance of my site, as a result im looking forward to use your awesome tool Lazy Load my question here is, in your examples you have given only URLS can i give PATH in place of URLS to call my JS.

Many Thanks

No, LazyLoad won’t load every file in a directory if you just give it a path. This isn’t possible, since there’s no way for LazyLoad to know what files are actually in that directory, and files must be requested individually over HTTP.

Hi, lazyload doesn’t seem to occur in Firefox 4.0.
Im trying to investigate why….

It’s working on Firefox 4.0, but sometimes, callback seems to occur before the end of the full load…

@MediaPod: Are you loading CSS or JS? JS should always get executed before the callback is called (if not, it would be a browser bug). CSS callbacks may fire before the CSS is fully loaded in Firefox, since Firefox doesn’t support onload on CSS nodes (a future version of LazyLoad will provide a workaround for this).

Hi, thanks for reply, i’m loading JS files.
I see FF4 has a completely different behaviour as FF3.6, really feal like a browser bug.

Make sure you’re using LazyLoad 2.0.1 (the latest version), not 2.0.0. It includes an update that deals with a change to the way JS files are loaded in Firefox 4. If you’re using 2.0.0, that may be what you’re seeing.

You’ll always find the latest version here: https://github.com/rgrove/lazyload

Copyright © 2002-2012 Ryan Grove. All rights reserved.
Powered by Thoth.