Reputation: 301
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?
Upvotes: 0
Views: 139
Reputation: 2134
$("#id")
is very much more efficient than $(".class")
-- the $(".class")
will iterate through the entire set.
a good way to vet this is :
var yourElement = $(".class");
for (var i=0; i< yourElement.length; i++)
{ alert(i);}
$("#id")
will return and run on only that one element (the first occurrence if there are improperly multiple id's with the same value even).
Edit: It additionally gets a little convoluted when the .children()
and .parent()
functions are used. These are related to what Jorge has mentioned below regarding the available arguments to the jquery selector native (and perform mostly the same)
@ Jorge - good observation
Upvotes: 2
Reputation: 79830
Just $('.someElement')
and $('#someOtherElement')
will be much better than using .find
as it uses native getElementsByClassName(..)
and getElementById(..)
native methods.
Upvotes: 1
Reputation: 11993
$('#id')
is the fastest way to do this
And you can save references for reuse later
var $cache = $('.cache');
Upvotes: 1