I'm building a site that is going to consist of components. A component defined as a particular set of HTML and CSS and jQuery. Each page of the site will consist of many components.
Per best practices, we're putting our javascript block at the bottom of the page. We load the needed .js files, and then I'm planning on calling the functions needed:
doThisThing();
doThatThing();
Let's say I have Component X. I want to call a function whenever that component appears on the rendered page. From a jQuery perspective, what would be the ideal 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, as we can just have one universal block of jQuery function calls. But there's a slight performance hit as it's searching the DOM looking for something that may not be there.
2) Attach the call to the component itself:
<div id="componentX">my component</div>
<script>$('.componentX').doYourThing()</script>
This is nice as it self contains the markup and .js calls in the same component. Drawbacks?
3) Integrate our component architecture with the back end system to allow the instantiation of components in the .js block. In otherwords, it'd check to see if the component is placed on the page temlate and, if so, will add the js function calls it depends on to the main script block.
4) other options I should consider?
UPDATE:
Based on kemp's answer, I thought I should clarify a bit. All of our jQuery functions will be wrapped up into one large compressed .js file, so in term of server hits, it's all the same. I'm more interested in how to best handle all the individual function calls for each component on the page in the context of individual page templates.
For instance, component X might be used on 90% of all pages. As such, calling the jquery function for those other 10% of pages doesn't seem like a big deal.
However, component Y might only be used on 5% of all the pages. I probably don't want to call the jquery function on each and every page as 95% of the time, it'd be unecessary.
A further scenario that might further complicate things: component Z might be used once on 100% of all pages, but twice on 5% of the pages.