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


Please Help Members By Posting Answers For Below Questions

What is the use of jQuery.ajax method ()?

468


How we can hide a block of html code on a button click using jquery?

480


Define type paremeter of jquery ajax method?

433


Do we need to add the jquery file both at the master page and content page as well?

453


How to get the direct parent of an element using ?

488






What are the guidelines for an application to follow the principles of progressive enhancement.

453


How to find all sibling elements after the current element using ?

481


What are the popular jquery cdn? : jquery mobile

449


Tell me how to check if number is numeric while using jquery 1.7+? : jquery mobile

476


Explain the use of data-role=”page” attribute? : jQuery Mobile

440


What is the difference between onload() and document.ready() function used in jquery?

785


Is jquery a w3c standard? : jquery mobile

513


Is jQuery a programming language?

478


Explain the animate function.

492


How did you become the creator of jquery ui? Whats the story behind that?

746