tags:

views:

113

answers:

5

I was just wondering whether this snippet of Javascript is going to slow down my site:

$(function(){
 var realLink = location.href;
 $( "#nav a" ).each(
  function( intIndex ){
   String.prototype.startsWith = function(str){
    return (this.indexOf(str) === 0);
   }
   var pageLink = $(this).attr("href");

   if ( realLink.startsWith(pageLink) )
    $(this).parent().addClass("active");   
  }
 );
});

It only loops about 5-7 times, and I don't have very much Javascript looping experience.

A: 

Should be fine. If the #nav element doesn't contain thousands of links you should be OK.

Install Firebug for Firefox and you can do a profile run. It will tell you how much time it spends in each function. My guess it will be in milliseconds for this case.

Igor Zevaka
+2  A: 

You could make that code perform a little better by changing it to:

String.prototype.startsWith = function(str){
    return(this.indexOf(str) == 0);
}

$(function(){
    var realLink = location.href;

    $('#nav a').each(function(intIndex){
        var pageLink = $(this).attr("href");
        if(realLink.startsWith(pageLink))
            $(this).parent().addClass("active");
        });
});

It just breaks out the definition of startsWith() so you don't define it for each iteration of the loop.

Justin Niessner
+5  A: 

There's nothing inherently wrong with this snippet, except that you're constantly creating and assigning a function to String.prototype.startsWith in a loop. That, of course, is an unnecessary work, and should at least be:

$(function(){
 var realLink = location.href;
 String.prototype.startsWith = function(str){
   return (this.indexOf(str) === 0);
 };
 $( "#nav a" ).each(
  function( intIndex ){
   var pageLink = $(this).attr("href");
   if ( realLink.startsWith(pageLink) )
    $(this).parent().addClass("active");   
  }
 );
});

I also don't see a need for intIndex argument there. It's not used anywhere in a function.

kangax
You're back! :-)
Crescent Fresh
That answers it! I didn't understand exactly what the string.prototype was doing (I am new to javascript outside of jQuery ironically)
Kyle
+1  A: 

Try using Firebug's Profiling Feature to measure the performance of your script.

Tobias Cohen
A: 

if you use the ^= operator in Sizzle (well, jQuery in this case) it means "starts with this value" basically. try this:

$(function(){
   $( '#nav a:not( [href^="' + startsWith + '"] )' ).addClass( 'active' );
});

and change startsWith to a variable of your choice.

Dan Beam