How to avoid parsing all the links on a page
There are a lot of different reasons to parse all the links on a page. Lightbox (and it’s Mootools counterpart, Slimbox) look through all the links to find the ones that need their magic. SmoothScroll loops through them to find all the links with in-page name anchors. Here at CNET, we’re starting to use javascript to insert our tracking logic into our links (instead of hard-coding them in the links in our templates).
For a page like one on CNET, this can mean having the browser iterate through document.links several times, and the result can really bog down a page.
I ran this code on cnet’s home page:
$A(document.links).each(function(lnk, index){
$(lnk).addEvent('click', function(){
alert('hi');
});
});
There are 332 links on the page, and this code took 190ms. Now, I could optimize this loop, but this is probably how someone who wasn’t working on optimize it might write it. For instance, using $$(’a') is actually twice is fast as $A(document.links).
Anyway, the problem is when you start adding these things up. If you solve this “I need to check all the links here” problem by iterating through, you might end up slowing the page down by half a second, which is when things start getting noticeable.
In a recent post on Ajaxian, I was directed to this article on using capture to steal the event. Using this method of adding events, you can add an event listener to the whole document.body. Then, on click, evaluate your code. If the link clicked meets your criteria, execute your code, else, follow the link.
Note that IE doesn’t use capturing, but I think you can still stop the event from propagating. I need to do some testing first.
