Question

I've been working on a rather large scale project which makes use of a number of different pages with some very specific Javascript for each of them. To lessen load times, I plan to minify it all in to one file before deploying.

The problem is this: how should I avoid launching page specific JS on pages which don't require it? So far my best solution has been to wrap each page in some additional container

<div id='some_page'>
...everything else...
</div>

and I extended jQuery so I can do something like this:

// If this element exists when the DOM is ready, execute the function
$('#some_page').ready(function() {
    ...
});

Which, while kind of cool, just rubs me the wrong way.

Was it helpful?

Solution

I have accomplished this by giving each page a unique id on the <body> element:

<html><head>...</head><body id="sign-in">...</body></html>

And writing all my page-specific scripts in jQuery blocks like so:

$(function(){
  if (!$('body#sign-in').length) return;
  // Code specific to sign-in page here
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top