How does caching helps and how to use caching in jQuery?
Answer Posted / 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 View All Answers
Why is only the first page of multi page document loaded? : jquery mobile
What is CDN?
Give a brief idea about jquery mobile? : jQuery Mobile
Can you give me a brief history of your programming days? Where did it all start?
Which operating system is more compatible with jQuery?
How can images be made to appear scrolling one over another?
Can jquery be used to make an ajax request?
How to check/uncheck an input in jquery?
Explain the difference between jquery's ready and holdready?
Explain the advantages of jquery?
Define "beforesend(xhr)" paremeter of jquery ajax method?
How does jquery store data related to an element?
What is difference between sorting string array and sorting numerical array in jquery?
explain width() vs css(‘width’) in jquery
Explain the animate function.