I am in the process of optimizing the JavaScript code used on our site and need some pointers/tips on what to do and what not to. We use jQuery 1.7.1 as our library.
When it comes to optimizing/writing an optimized code, I am still a novice, but what I do know is that we need to reduce the number of DOM traversals.
So, what I am thinking about is to cache the elements used more often and then use the cached elements for whatever reasons.
What I am confused or should say am curious about, how about if on DOM ready, I cache the "body" element in a variable of global scope and then use it in all JavaScript code/files to find any element(s) I may need there after.
like
jQuery(function(){
myGlobalObj.body = jQuery('body');
..
..
..
myGlobalObj.body.find('.someElement').<whatever>;
..
..
..
myGlobalObj.body.find('#someOtherElement').<whatever>;
..
..
..
});
Will it prove to be useful for improving performance? Are there any adverse effects, like not getting updated DOM tree, or something?
Please advice.
Edit #1: Thanks for the comments and answers guys, but I guess I did not make myself clear.
I know the benefit of using an ID based selector over the one with a className, but what my concern was that will performance increase by using a cached reference of "body" (or the closest filtered parent of the searched element) for searching/isolating the target elements.
i.e. instead of using $(..whateverElement..) every-time,
will $cachedParent.find(..whateverElement..) prove to be a better performer or not?