Sunday, June 15, 2008

(Very) lazy loading in javascript

Using the "lazy loading" in javascript is a common technique to minimize the startup time of a web application.
Usually a single object is retrieved from the server with its own members and methods: but why not use instead of the methods a stub which loads the method source when is called the first time?
For example, a singleton object like this, having two methods:
var application = {
sum: function(){
return arguments[0] + arguments[1];
},
product: function(){
return arguments[0] * arguments[1];
}
};

could be written as (you can use your preferred ajax framework/library; remember: use a synchronous call):

var application = {};
var names = {
"sum" : "sum.js",
"product" : "product.js"
};
for(var i in names){
application[i] = function(x){
return function(){
dojo.xhrGet({
url: names[x],
sync:true,
handleAs:"text",
load: function(data){
application[x] = new Function(data.replace(/\n/g, ""));
},
error: function(err){
window.alert("[error] " + err);
}
});
return application[x].apply(this, arguments);
}
}(i);
}
Oh yes, this is a stupid example, the stub method is greater than the real method, but it's only a proof of concept ;)
You can find a live example here

Labels: , , , ,

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home