Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching $(this) in jQuery is a best practice?

We all know it's good to cache calls to the DOM, so instead of calling $('#someElement') more times, just save it to a var $someElement and use that.

But is it the same when using $(this) inside an event listener for example? Should $(this) be cached?

Thank you.

like image 500
Francisc Avatar asked Mar 07 '12 14:03

Francisc


People also ask

Should I cache jQuery?

In case you are not adding or removing DOM elements, you should always cache the results of your jQuery selectors.

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

Caching enhances the performance of the application. Cache your jQuery selectors for better performance. This can be done using the ID as your selector. For example, this caches the selector and stores it in variable.

Does jQuery cache selector?

jQuery Sizzle does automatically cache the recent functions that have been created from the selectors in order to find DOM elements. However the elements themselves are not cached.


2 Answers

Each time you call $(this) or $(selector) it is a function call to create a new jQuery object... so if you have already created it once, caching will save calling a function to create the same object again

like image 60
charlietfl Avatar answered Sep 22 '22 10:09

charlietfl


If you call $(this) multiple times, it is better to do something like var $this = $(this);

like image 37
xdazz Avatar answered Sep 21 '22 10:09

xdazz