I typically put all the JavaScript scripts into one file e.g. scripts.js (the less HTTP request, the better). So, as expected, some scripts are needed for some pages, some aren’t.
To target a specific page, I use something like:
if ($("body#share").length > 0) {
// Place the logic pertaining to the page with ID 'share' here...
}
// The file / script continues...
Other or better suggestions? Thanks!
Clarification: I was not looking for the pros / cons between consolidating multiple JS files into one big file and keeping multiple separate JS files. The answer for this is surely ‘depends on the situation’ (we know that). My question is, assuming all my JS logic is placed into one big file, how do I make a particular (chunk of) script runs only when the corresponding page is loaded? One way I used to do is using if ($('#id-of-target-element')) { /* run the script */}; is there a better way?
I like Paul Irish’s approach… you don’t have to follow it exactly, but the general idea is a very solid one.
It might look something like this for your example
Html
Your page specific javascript
Paul Irish’s Javascript that makes the magic happen
So the line you see directly above will kick off the following
Have a read of his blog post and a few of the variations linked from it.