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 |
Does jQuery 2.0 supports IE?
Can you please explain the difference between .js and .min.js? : jquery mobile
What is wrong with this code line "$('#myid.3').text('blah blah!!!');"
List the basic selectors in jquery?
What is the basic requirement to start with the jquery?
How to call a method inside code-behind using jquery?
Difference between $(this) and 'this' in jQuery?
Explain the difference between find and children methods in jquery?
What are the two types of CDNs?
How do you check if an element is empty?
How to execute jQuery code after the DOM is ready?
What are selectors in jquery? Explain