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 |
How do you select element by ID in jQuery?
Tell me how to select combobox select value and text using jquery?
Tell me how to write browser specific code using jquery? : jquery mobile
Please tell us that is jquery knockkout intended to compete with jquery or prototype or work with it?
Why do we use jquery? : jquery mobile
Can you use multiple document.ready() function on the same page?
What are the effects methods used in jquery?
Is it possible to use jquery to make ajax request? : jquery mobile
Explain the use of the $.fn.bind and $.fn.trigger.
Tell me an example usage of jquery mobile? : jquery mobile
How do you install/use jquery in a project.
Name 3 available jquery plugins that bootstrap has in their query plugin library.