2

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.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91

1 Answers1

3

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
});
Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • That's actually essentially how I did my jQuery edit and I guess that seems to be the best way of going about it. Thanks. – Mike Cluck Jul 10 '12 at 14:45
  • I've been looking everywhere for this kind of answer and could never find it since Google keeps giving me advice to the keyword search "conditionally load JavaScript" in a non-minified environment. Do you know if doing the detection via JS is an accepted best-practice as of 2014, or should I be relying on my build tools? – Bill Mei Aug 28 '14 at 00:43