I am working on refactoring a JavaScript namespace for a site. The namespace leverages jQuery for selectors and events. Here is an example.
MyNamespace = {
eventElements : {
headerSectionA : $("h1.section-a");
headerSectionB : $("h1.section-b");
}
sectionA : function() {
// do stuff for section A here, such as
MyNamespace.eventElements.headerSectionA.click(function(){
// behavior A
});
}
sectionB : function() {
// do stuff for section B here, such as
MyNamespace.eventElements.headerSectionB.click(function(){
// behavior B
});
}
}
This is a distilled code sample. Imagine many eventElements, and many site sections that make use of subsets of those eventElements.
My question is whether jQuery traverses the DOM for all eventElements every time this script loads, or only when a function is called that uses that eventElement.
I want to avoid performance loss, but I am not sure if jQuery traverses the DOM when an eventElement property is declared, or only when an event is attached to the eventElement.
If there is a performance loss using the approach above, then I will branch within the namespace to only declare eventElements within the context of the section that makes use of those eventElements.