title: I keep everything in an external .js file. But not all functions are used on every page. Does this affect speed?
body: <p>My app's JavaScript/jQuery is contained in an external <code>scripts.js</code> file. It generally looks like this:</p>
  
  <pre><code>$('document').on('ready', function() {
      giraffe();
      elephant();
      zebra();
  });
  
  function giraffe() {
      // code
  }
  
  function elephant() {
      // code
  }
  
  function zebra() {
      // code
  }
  </code></pre>
  
  <p><code>giraffe()</code> is only used for the view available at <code>/animal/giraffe</code><br>
  <code>elephant()</code> is only used for the view available at <code>/animal/elephant</code><br>
  <code>zebra()</code> is only used for the view available at <code>/animal/zebra</code>,</p>
  
  <p>But all 3 are supposed to run on the view available <code>/animal/all</code>. This is a rudimentary example, but this is the reasoning behind having them all in one <code>.js</code> file, apart from keeping HTTP requests to a minimum.</p>
  
  <p>My question is, does this affect the JavaScript rendering? Even though <code>giraffe()</code> isn't used (has no elements to work on) on <code>/animal/zebra</code>, it's still being called. Does js/jQuery ignore the function if it finds nothing to do? I'm sure the whole script is read, and that probably takes time. So, what's best way to handle this?</p>
  
  <h2>One solution</h2>
  
  <p>To avoid conflicts, I've created conditionals at the top of the js file to only run the functions that the active page needs:</p>
  
  <pre><code>$('document').on('ready', function() {
      var body = $('body');
  
      if( body.hasClass('giraffe') ) {
          giraffe();
      }
  
      if( body.hasClass('elephant') ) {
          elephant();
      }
  
      if( body.hasClass('zebra') ) {
          zebra();
      }
  });
  </code></pre>
  
  <p>This is a little more verbose than I would like, but it is successful in keeping these functions modular/conflict free. I welcome an improvement on this solution.</p>