How does caching helps and how to use caching in jQuery?

Technology CommunityCategory: jQueryHow does caching helps and how to use caching in jQuery?
VietMX Staff asked 3 years ago

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.

$("#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,

```js
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