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.
In case you are not adding or removing DOM elements, you should always cache the results of your jQuery selectors.
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.
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.
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
If you call $(this)
multiple times, it is better to do something like var $this = $(this);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With