I am creating a website that will consist of components. A component defined as a specific set of HTML and CSS and jQuery. Each page of the site will consist of many components.
In the best recommendations, we put our javascript block at the bottom of the page. We load the necessary .js files, and then plan to call the necessary functions:
doThisThing(); doThatThing();
Say I have an X component. I want to call a function whenever this component appears on the page that is displayed. From a jQuery perspective, what would be the perfect way to handle this? Some options:
1) Always call the function regardless of whether the component is on the page or not:
$('.componentX').doYourThing()
This is easy, since we can simply have one universal block of jQuery function calls. But there is little performance, as it searches for the DOM in search of something that might not be there.
2) Attach the call to the component itself:
<div id="componentX">my component</div> <script>$('.componentX').doYourThing()</script>
This is good because it itself contains markup and .js calls in one component. Disadvantages?
3) Integrate our component architecture with the back system to instantiate the components in the .js block. In other words, he would check if the component would be hosted on the temlate page and, if so, would add js function calls that depend on the main script block.
4) other options that I should consider?
UPDATE:
Based on kemp's answer, I thought I should clarify a bit. All our jQuery functions will be wrapped in one large compressed .js file, so itβs all the same from the point of view of server hits. I'm more interested in how best to handle all the individual function calls for each component on the page in the context of the individual page templates.
For example, component X can be used on 90% of all pages. So calling the jquery function for these other 10% of the pages doesn't seem like a big deal.
However, component Y can only be used on 5% of all pages. I probably don't want to call the jquery function on every page as 95% of the time, this would be necessary.
The following scenario, which can further complicate the situation: the Z component can be used once on 100% of all pages, but twice on 5% of pages.