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?