I’ve got a question about treating references to jQuery objects.
Let suppose in my app I have a DOM element DIV with ID=some_widget, it is supposed to live during all the application runtime and be used quite often in the code.
1) So if I keep a reference to it in a global var during application runtime:
var someWidget = $("#some_widget")
it will create jquery objects once, but will consume memory during application run, but when I use someWidget it wont create jquery object again, so this can speed up the process.
2) if I will alway use the call of $(“#some_widget”) in the code, it won’t consume memory constantly, but every time I use $. it will take time jQuery to construct the object.
Am I right? What approach is more sufficient?
Can keeping the references to many object end up with memory leak?
what does it depend on, what do you think?
Yes, you can cache your jQuery object by declaring it in a variable. This is in fact considered a best practice for re-used objects.