@Blog.Author(Nandip Makwana) .LearningExperience(ASP.NET, ASP.NET MVC, IIS, jQuery & Technology Surrounding it...)

December 22, 2011 comment ,

Efficient Use Of jQuery Object

Day by day, jQuery is becoming a more popular and it is widely used instead core JavaScript. With ASP.NET & ASP.NET MVC also there are so many good examples available on net to get best of both. Moreover default project template of ASP.NET MVC is also including latest jQuery file for easiness of client operation.

To perform any jQuery operation, first we need to select target DOM element or set of DOM elements. And we are living (rather programming) in the era of web 2.0 and Mashup where web documents are suppose to be large with few hundred elements and lots of client side operation as well. So here we will see how one small tip can be helpful to improve jQuery performance.

Many a time we have seen developer to perform a various operation on a specific DOM element or specific set of DOM element as described below.

$("#MyDiv").show();
$("#MyDiv").addClass("header");
$("#MyDiv").css("height","100");

However nothing is wrong in above code and it will works fine without any error. But there is a lot to improvements in above code. In above example we are selecting "MyDiv" elements three times; means for each of three operations, jQuery will search for "MyDiv" in whole document and then after it will perform specific operation on it. There are two different ways to overcome this overhead. Both are explained below.

jQuery Chaining 'em up

$("#MyDiv").show().addClass("header").css("height","100");

As displayed in above example, if we are supposed to use specific DOM elements or set of DOM elements in one code block only, Then we should use jQuery Chaining pattern as displayed above. In this it will select "MyDiv" only once. As we know that after performing any jQuery operation, it will return jQuery object so we can directly use that returned jQuery object to perform next operation and can form chaining pattern.

Cache jQuery Object

var myDivElement = $("#MyDiv");
myDivElement.show();
myDivElement.addClass("header");
myDivElement.css("height","100");

jQuery chaining pattern is suitable when we are suppose to perform multiple operation in one code block only, but it will not helpful when we have to perform multiple operation from different-different code block. In such situation we should cache jQuery object as displayed in above example and then after use cached object instead selecting it each and every times.

Hope this would be helpful.

comments powered by Disqus

Featured Content

Resources & Tools

About Nandip Makwana

Nandip Makwana is passionate about digital world and web. He completed his Masters in Computer Application in June 2011. Currently he is working as a Software Engineer. He has shown great promise and command over ASP.NET and technologies surrounding it during his academic years and professorial life...continue reading