Prototype(.js) $() function. The Devil’s In The Details.

Although the ubiquitous $() function of prototype.js helps developers from retyping the DOM methods for getting an element, it should be used with utmost care. As they say ‘the devil’s in the details‘, we take a look at the protoype definition for $():

function $() {
var elements = new Array();

for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == ’string’)
element = document.getElementById(element);

if (arguments.length == 1)
return element;

elements.push(element);
}

return elements;
}

As we see above, the document.getElementById(element) is called on every function call. Therefore all the $() function does is facilitate code resuse.

But I have seen developers use the $() without regard to its implementation just because its handy, short and sweet. People tend to write code like the following:

for(var i=0; i< $('element').length; i++) {
var value = $(’element’).value;
…….
}

Here in effect, for every iteration the DOM dynamically looks up for the element. This is inefficient which can be avoided using Object Caching (storing the objects referenced many times into a local variable). Here is the same code using object caching:

var element = $(’element’);
for(var i=0; i
var value = element.value;
……..
}

Sometimes these minute details can make a big difference.

Leave a Reply

Popular Tags

AJAX algorithm Artificial Intelligence artificial intelligence BarCamp bayesian blogger Blogging cache database delicious design event extension firefox gmail Google humor India Interview knowledge lifelogger Linux Lucene Machine Learning machine learning misc Mozilla mplayer Open Source open source patterns Performance plugin Project pune Ruby Search sergey brin Social Networks social networks Tagging thunderbird thunderbolt Trends visualization Web Web 2.0 yahoo Yahoo!