Oct 26 2007

Javascript include: import a .js file from a .js file

Tag: Computer World,Howtosjdoe @ 3:41 pm

* this post is in english. if you want to code javascript you have to know english, so it’s a non-sense to write this in italian *

Well for those of you that are approaching javascript and miss something like php include/require, python import ecc ecc this is somthing that works in a similar way
The “normal” way for doing this in javascript is to add a <script> tag

<script src="/path/to/file/to/include.js" type="text/javascript"></script>

Well, I don’t like this, cause when I’m editing the js file I don’t explicit which are the file’s deps.
So I’ve wrote a simple function for doing explicit including, lurking the MochiKit source code and basically copying from there.

var included_js = {};
var namespaceID ="ExampleCom";

function include(url,id)
{
	var kXULNSURI = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

	/* prevent re-include */
	if (url in included_js)
		return;

    if (document.documentElement &&
        document.documentElement.namespaceURI == kXULNSURI) {
        /* XUL based browsers */
        var s = document.createElementNS(kXULNSURI, 'script');
        s.setAttribute("id", namespaceID + "_" + id);
        s.setAttribute("src", url);
        s.setAttribute("type", "application/x-javascript");
        baseElem.parentNode.appendChild(s);
    } else {
    	/* not XHTML standard :(  */
    	document.write('<script src="' + url + '" type="text/javascript"></script>');
    }
    included_js[url] = true;
}

This function really doesn’t do anything that you can do yourself, it just prints out the <script> tag for you (or, if browser is mozilla, use the DOM/XUL to load the file)
I want to improve this function to:

  • Avoid loading the script two time – updated!
  • Permit a behavior similar to require

The usage is really as you can read from the short code above:

include('/path/to/file/to/include.js', 'FILEID');

Where FILEID is a string that identify the javascript file