load-time-js-http-graphsI've written a couple articles on this blog that speak to the advantages of keeping all of your JavaScript in a single file, even it's not used on every page (running portions of the script conditionally based on url, existence of an element or some other factor).

The graph at the right explains this concept visually. Because each JavaScript file requires a separate HTTP connection to load it, the load time increases exponentially as the number of individual files load increases. So, have loading 10 files, each with 50 lines of code will take a great deal longer to load than a single file with 500 lines of code.

There are cases, though, where it doesn't always make sense to lump a piece of JavaScript in the main script file. Two reasons come to mind:

  1. You don't want a certain piece of JavaScript to have the same caching directives as the main file.
  2. A piece of JavaScript is relatively large, but is very seldom executed.

In both instances above, it does actually make sense to create a separate script file for this piece of code. When it's loaded, you'll of course have the extra HTTP connection. But, you can still load the file asynchronously from the main JavaScript file as needed.

By including the "secondary" JavaScript file from the "primary" JavaScript file, you allow the primary JS file to become a controller, which helps keep your script organized. It also allows you to load your script in a far more consistent fashion than if you had added a <script> tag to the individual page that requires it.

The jQuery code below demonstrates this:

if ($('body.edit-page.edit-location').length !== 0) {
  (function() {
    var js = document.createElement('script');
    js.type = 'text/javascript';
    js.async = true;
    js.src = '/src/js/location-edit.js';
    var scriptTag = document.getElementsByTagName('script')[0];
    scriptTag.parentNode.insertBefore(js, scriptTag);

As a final note, you'll notice that we've wrapped the asynchronous JavaScript file load in a function block. We do this so we don't have to create the js variable in the global namespace. This will prevent variable naming conflicts, as well as keep your code a little cleaner (the js variable is destroyed after the script is loaded).


Leave a Reply

Your email address will not be published. Required fields are marked *