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

Difference between event.PreventDefault and event.stopPropagation?

517


What are the slow selectors in jquery? : jquery mobile

450


Do you have plans for a new jquery plug-in or something else we should look out for? Where to from here for the imgpreview plugin?

478


What features of jquery, has been used in web applications?

463


How to use migrate jquery plugin if possible? : jquery mobile

471






Write the code to define a requirejs module with its dependencies.

467


How to prevent Right Click option using jquery?

488


How do you install/use jquery in a project. What is the minimum setup needed to start using jquery.

459


Tell me which command will give a version of jquery?

412


What is the use of jquery.data()?

477


Can we select a element having a specific class in jquery ?

455


What are your tools of choice to get the jquery job done?

477


Can we call c# codebehind method using jquery?

411


How to search for descendant elements that match the specified selectors using ?

448


What is the struts2 jquery plugin and its advantages.

503