Efficent Javascript for better YUI Compression

Posted: February 16, 2011 in Javascript, Performance
Tags: ,

Efficient way of writing javascript for better YUI Compression …

  • Use <cond>?s1:s2 in place of

if(<cond>){
s1
} else {
s2
}

  •  Use obj.toggleClass(“c1”, cond); in place of

if(cond) {
obj.addClass(“c1”);
} else{
obj.removeClass(“c1”);
}

  •  Use local variables for true/ false, null, empty string if used in multiple places

Define => var TRUE = true, FALSE = false, NULL = null; and use it.

  • Use single var and Single return in a function.

var a = 1, b = 2;  instead of var a = 1; var b = 2;

  • Chain It obj.addClass(“c1”).attr(“data-something”, “something”).show(); instead of

obj.addClass(“c1”); obj.attr(“data-something”, “something”); obj.show();

  • Think before using substring

str.substring(1) to str.slice(1) –To Chop off 1st Character str.substring(str.length – 1) to str.slice(-1) –To get last Character

  • Use if(s.length) instead of if(s.length > 0)
  •  i= i + 1 => i+=1 => i++
  • {“a”:123, “b”: “123”} => {a:123, b:123}
  • Use variables to define literals that used in many places …

Ex: var c1 = “pause”, c2 = “playing”;
if(isPlaying) $.addClass(c1).removeClass(c2); else $.addClass(c2).removeClass(c1);
In place of

if(isPlaying) $.addClass(“pause”).removeClass(“playing”); else $.addClass(“playing”).removeClass(“pause”);

Reference:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s