Javascript Includes

Published July 19th, 2006 under JavaScript, Web Development
by Mashhoor Al Dubayan

That’s one thing I’ve always wanted to do in JavaScript - calling a script from within another script, like the @import command in CSS or include in PHP/C/C++. JavaScript doesn’t support this natively. I thought there’s no workaround until today my friend, Egor Kouchnarev, who is web designer, asked me whether it’s possible to do this using document.write to write some <script /> tags/links in a document’s head. It was a pretty good idea, except It’s better implemented by manipulating the DOM.

So I’ve made a little script today to achieve this, and it worked pretty well:

function includeFiles()
{
  // you can add more files if you want
  var scripts = ["file1.js", "file2.js"];

  var scriptElement = new Array(scripts.length);
  var headTag = document.getElementsByTagName("head")[0];
  var fragment = document.createDocumentFragment();

  for(var i=0, count = scripts.length; i < count; i++)
  {
    scriptElement[i] = document.createElement("script");
    scriptElement[i].setAttribute("src", scripts[i]);
    fragment.appendChild(scriptElement[i]);
  }

  headTag.appendChild(fragment);
}

function addEventHandler(oTarget, sEventType, fnHandler) {
    if (oTarget.addEventListener) {
        oTarget.addEventListener(sEventType, fnHandler, false);
    } else if (oTarget.attachEvent) {
        oTarget.attachEvent("on" + sEventType, fnHandler);
    } else {
        oTarget["on" + sEventType] = fnHandler;
    }
};

addEventHandler(window, "load", includeFiles);

You only need to call this file from an HTML document, then specify the path and/or name of other scripts in the scripts array. You can add more elements if you wish; its not limited to two files. You can download an example I’ve made earlier if this wasn’t clear, or download the script alone.

The advantage of this script is the ability to change the included script(s) in a document by modifying one file only (the include script). On the other hand it might create a small, unnecessary overhead that could be avoided by sticking to the traditional way of including scripts.

The scripts has been tested under Internet Explorer 6, Firefox 1.5, and Opera 9. I didn’t use feature-sniffing in this version of the code to keep it simple and clear. Your feedback is welcome.

5 Responses to “Javascript Includes”

  1. 1 davidbisset.com » Javascript Includes

    […] Calling a script from within another script in Javascript. […]

  2. 2 Aaron Bassett

    The Scriptaculous library has been doing something like this for a while now. But they recommend not using the DOM as it fails in Safari - I’ve included the relevant code from scriptaculous.js below. You can get the full library from http://script.aculo.us/

    var Scriptaculous = {
    Version: ‘1.6′,
    require: function(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write(”);
    },

  3. 3 Aaron Bassett

    Sorry some of it got stripped out here is full code

    var Scriptaculous = {
    Version: '1.6',
    require: function(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('$lt;script type="text/javascript" src="'+libraryName+'"></script>');
    }

  4. 4 Mashhoor Al Dubayan

    That’s weird; I assumed Safari already supports it. Too bad i don’t have a mac to test on.

    I guess I’ll have to ignore those 12 people out there who use Safari ;). (kidding)

  5. […] Readmore from Author’s Website […]

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>