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 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.
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.
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 (el.currentStyle) { // IE
return el.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(el, '')[property];
};
} else if (el.currentStyle) { // IE
getStyle = function(element, property) {
return el.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.
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.
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.
A few panoramic shots I took at SDCC 2010. #geek http://bit.ly/bwX6GB
JS version of Regex prime number checker:
function isPrime(n) {
return Array(n + 1).join("1")
.search(/^1?$|^(11+?)\1+$/) == -1;
}
Погрузился в пучину EcmaScript5, местами увлекательно, местами нудно =)
Modernizr http://ow.ly/18njQ1
A Collection of 20 HTML5 Video Players - a round-up of JavaScript and html5 alternatives to Flash-based media player... http://ow.ly/18njQ2
jQuery TOOLS - The missing UI library for the Web http://ow.ly/18njQ3
Contactable - A jQuery Plugin | the odin http://ow.ly/18njQ4
Giants vs Dodgers, sweet seats. http://twitpic.com/2ag9pa
@snookca That'll be fixed next week. I promise.
@snookca I was tryna not name names ;) But really that was just par for the course today, pretty hectic day. As I'm sure you know.
Who breaks major stuff after 4pm on Friday? On the last day of the sprint, no less. Tsk. (wasn't me)
Awesome live git tracker for teams: http://www.utsup.com/
RT @DerrenBrown: Blog post: Camera Software Lets You See Into the Past http://bit.ly/9kjVg5
10 invites to the new version of Digg: http://bit.ly/dqM8EV
Threaded vs Evented Servers, great look at the whats and whys. http://bit.ly/bDUEjn #geek
Nav, Context menus, "app-style" toolbars in sample chapter http://bit.ly/csTRY8 of new YUI book http://bit.ly/cJINoV
Add a side-mounted End Call button to your iPhone 4: http://bit.ly/cGxPBD #funny #geekAll 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!