I recently read some articles regarding jQuery performance, and I came up with some weird questions.
Can/Should I cache
$(window)
?If I did, would it affect
resize
,scroll
,width
,scrollTop
...etc?Can/Should I cache
$(document)
?As we use a lot of mouse actions, should I do
var doc = $(document);
?Can I always cache
$(this)
in a big block of code?As for
var self = $(this);
, in what condition thatself
might be different from$(this)
?
All three questions: Yes You can!
Neccessery : no
Better performance: maybe
You could try and do a benchmark. But the reason for caching is not to search entire DOM for your selector. Looking up document and window isn't a problem because they are 2 root variables. Caching $(this) depends on situation. See my 2nd tip.
Always cache the parent object you run queries on:
It’s better to chain the jQuery methods than to cache the selectors:
Cache elements that you query often:
A free extra performance tip:
Selectors fastes to slowest:
Yes, you can cache $(window), and it does help on performance.
Someone already did a test in jsperf. http://jsperf.com/jquery-window-cache
The test result is kind of messed up, but you can still "Run test" on your browser to see the difference.
Yes, you can cache $(document) as well. I don't use $(document) much, but base on the test I made in jsperf (http://jsperf.com/document-vs-cache), caching $(document) do help on performance a bit too.
And yes, you can cache $(this). But this one is different than the other cahces. As you already know, value of $(this) will change depend different situation. For example, if you use $(this) in mouse listener like this....
$(this) will change when user click on the button with the class "button", and $("this") will become the object which clicked by user.
Caching $(this) can help on performance if you use $(this) a lot inside the function. But remember that if you cache $(this) inside the function, the cache will become a local variable instead global, and will be destroy at the end of the function. So you won't able to use it outside the function.
Actual question is,
Can I cache $(window) and $(document) in jQuery?
If you want to cache the window or document for further use in the same session, yes you can.
All the variables/functions you created will be garbage collected if user closes the window/session.