How does caching helps and how to use caching in jQuery?



How does caching helps and how to use caching in jQuery?..

Answer / chaitanya

Caching is an area which can give you awesome performance, if used properly and at the right place. While using jQuery, you should also think about caching. For example, if you are using any element in jQuery more than one time, then you must cache it. See below code.

Hide Copy Code

$("#myID").css("color", "red");

//Doing some other stuff......

$("#myID").text("Error occurred!");



Now in above jQuery code, the element with #myID is used twice but without caching. So both the times jQuery had to traverse through DOM and get the element. But if you have saved this in a variable then you just need to reference the variable. So the better way would be,

Hide Copy Code

var $myElement = $("#myID").css("color", "red");

//Doing some other stuff......

$myElement.text("Error occurred!");



So now in this case, jQuery won't need to traverse through the whole DOM tree when it is used second time. So in jQuery, Caching is like saving the jQuery selector in a variable. And using the variable reference when required instead of searching through DOM again.

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More jQuery Interview Questions

What are the advantages of using cdn?

0 Answers  


Which are the popular jQuery CDN? and what is the advantage of using CDN?

1 Answers  


Tell me how do you stop the currently-running animation? : jquery mobile

0 Answers  


What is the use jQuery.data method?

0 Answers  


What is the difference between settimeout() and setinterval() methods?

0 Answers  






Explain remove class jquery with example?

0 Answers  


Explain data paremeter of jquery ajax method?

0 Answers  


How we can select multiple elements in jquery?

0 Answers  


What are the selectors in jquery? How many types of selectors in jquery?

0 Answers  


What is difference between sorting string array and sorting numerical array in jquery?

0 Answers  


What's next on the hitlist with jquery ui?

0 Answers  


How to include jquery library in asp.net project?

0 Answers  


Categories