I am using jQuery and I am loading dynamic HTML via PHP. My question is, what is the best practice concerning elements/attributes that may or may not exist on any given page? Should I have one .js file containing all the possibilities (I would think this is inefficient) or should I use a bunch of script tags (that seems also inefficient)? Is there a “lazy” initialization way to do this?
For instance, say I have the following:
<div id="list">
<ul>
<li>some</li>
<li>stuff</li>
<li>here</li>
</ul>
</div>
But this list is generated only if necessary, not on all pages. Should my global js file have the following:
$("#list").click( function(){
$(this).removeClass('collapse').addClass('expand');
});
Or should I add it in a script tag just above the div that is being generated at the bottom of the page after creating the div is output via PHP?
Thanks SO, you guys are awesome. Can’t wait until I know enough to start answering some questions!
Edit, just thought of a quick way to ask. Which is better, jQuery running with a bunch of selectors that don’t match or passing javascript in script tags via PHP?
2 Things:
Loading 1 big js file is faster than loading many small ones, as it avoids the overhead of many connections
If your can tell clients to cache the js then it will only be loaded on the first visit.
Also you say add it to the HTML just above the tag. When a web browser encounters JS it stops rendering until the JS is loaded and executed. So you want to put the JS at the bottom of the page, so your page appears to the user as soon as possible.
Not that I’m saying 1 big file is the way to go mind, it depends on many things. These are just things to bear in mind.
EDIT TO ADD: But I would definitely put it in external js and not HTML, so you can get client side caching working for you. And call those JS from the bottom of your page so as not to block rendering. Sorry, this is a bit of a messy answer but this is a big topic, there are many factors to consider and no right answer.