arguments.callee web design & development blog  


JavaScript Design Patterns: Lazy Initialization

Lazy initialization (also called lazy function definition or lazy loading) is a creational design pattern which often boosts performance. It's how you can avoid repeating an "expensive" process — creating a large or complex object, performing a difficult calculation, or spinning in a long loop. Lets take a look at a few variations of this design pattern.

On-Demand Script Loading

On-demand loading is becoming more widespread across JavaScript libraries. One big example is Yahoo's YUI3; their library begins small and loads additional chunks as required. By reducing the initial payload, on-demand loading can make your site load faster and be more responsive.

Outside of libraries, there are many ways to dynamically load scripts. Nicholas Zakas suggests this as the best method for loading external JavaScript files:

    function loadScript(url, callback){
        var script = document.createElement("script");
        script.type = "text/javascript";
        if (script.readyState) { // IE
            script.onreadystatechange = function() {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else { // not IE
            script.onload = function() {
                callback();
            };
        }
        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }
    <!-- loadScript.js contains loadScript() as defined above -->
    <script type="text/javascript" src="loadScript.js"></script>
    <script type="text/javascript">
        loadScript('/js/BigScript.js', function() {
            var o = new BigObject(); // assume this constructor is defined in BigScript.js
        });
    </script>

By deferring BigScript.js, the page appears to finish loading before that file is even fetched. The file loads "behind the scenes", letting your visitor start interacting with your site sooner.

Lazy Factory

A Factory generates an object when it is needed. A Lazy Factory actually generates the factory. One common Factory example is the XMLHttpRequest object used to make AJAX calls:

    function getHttp() {
        if (typeof XMLHttpRequest != 'undefined') {
            return new XMLHttpRequest();
        } else if (typeof ActiveXObject != 'undefined') {
            return new ActiveXObject("MSXML2.XMLHttp");
        }
    }
    var http = getHttp();

Every time you call getHttp(), your code checks for the existance of XMLHttpRequest, and then possibly checks for the existance of ActiveXObject. Really, these checks only need to be made once, because the results will always be the same under normal circumstances. Lazy Factory to the rescue:

    function lazyHttp() {
        if (typeof XMLHttpRequest != 'undefined') {
            lazyHttp = function() { return new XMLHttpRequest(); }
        } else if (typeof ActiveXObject != 'undefined') {
            lazyHttp = function() { return new ActiveXObject("MSXML2.XMLHttp"); }
        }
        return lazyHttp();
    }
    var http = lazyHttp();

The first time lazyHttp is called, it actually redefines itself based on the current environment. The second time it is called, lazyHttp returns the proper object directly, no checks required. More complex factories might skip whole blocks of code, resulting in increased savings.

Lazy Function Definition

Closely related to the Lazy Factory is Lazy Function Definition. The first time a lazy function is called, it redefines itself based on a one-time calculation or evaluation. Often, JavaScript libraries implement this pattern when retrieving CSS style information:

    // these IF statements will be tested every time getStyle is called
    function getStyle(element, property){
        if (document.defaultView && document.defaultView.getComputedStyle) { // not IE
            return document.defaultView.getComputedStyle(el, '')[property];
        } else if (element.currentStyle) { // IE
            return element.currentStyle[property];
        }
    }
    
    // these IF statements will be tested only the FIRST time getStyle is called
    function getStyle(element, property) {
        if (document.defaultView && document.defaultView.getComputedStyle) {
            getStyle = function(element, property) {
                return document.defaultView.getComputedStyle(element, '')[property];
            };
        } else if (element.currentStyle) { // IE
            getStyle = function(element, property) {
                return element.currentStyle[property];
            };
        }
        return getStyle(element, property);
    }

Because a Factory is technically just a function, these two implementations are basically identical. The difference is a conceptual one — factory methods typically return an object, either through new or the object literal {}. Generic lazy functions may return any type.

Extreme LFD, or "But when will I really USE this?"

JavaScript is a powerful language, and can represent powerful constructs such as the Y combinator:

var Y = function(F) {
    return (function(x) {
        return F(function(y) {
            return (x(x))(y);
        });
    })(function(x) {
        return F(function(y) {
            return (x(x))(y);
        });
    });
};

It's way beyond the scope of this particular post to explain how the Y Combinator is derived and used, but here's a fantastic explanation along with a demonstration which calculates the 100th Fibonacci number instantly, though a recursive (and non-lazy) implementation would take... well, in most browsers it would never return.

Tags




blog comments powered by Disqus
search blog
  • Build-Your-Site-Right-Using
  • Secrets-JavaScript-Ninja-John-Resig
categories & tags
random posts
about hb stone

I'm a Front-End Engineer at Yahoo! working on the Mail and Messenger teams. I blog about web design and development topics including accessibility, usability, performance, and developing HTML / CSS / JavaScript applications on Appcelerator Titanium and Adobe AIR.

If you're a web developer, you might enjoy Jelo, my JavaScript library.

  • Deploying-HTML5-Aditya-Yadav
  • Programming-Collective-Intelligence-Building-Applications
copyright

All original work on this site is covered by a Creative Commons Attribution 3.0 license unless otherwise specified.

You may share or use any code or images from this site in any manner, for free, so long as reasonable effort has been made to give credit where due.

The views expressed in the posts and comments on this blog do not necessarily reflect the views of Yahoo!