require_once, #include in JavaScript

If you've ever used C/C++, you can include more code by simply using #include and that header file gets included. The same thing goes for PHP, if you divide your program into multiple files you can include the code using include/include_once or require/require_once. If you are looking for something similar in JavaScript, you won't find any way of including more code. This is when I came up with this code, though later on while searching on the net I could see samples using a similar approach. But in any case this might help you to include code in your JavaScript files.

function include(fileUrl) {
var script = document.createElement("script");
var head = document.getElementsByTagName('head').item(0);
script.src = fileUrl;
head.appendChild(script);
}

To include a file in your JS code you can use include("<url of js>"). If you look at the code, we are creating a new <script> tag in the <head> section of the document. This works in Firefox, IE & Opera, and I think it should work in other browsers also, but I have not tested it out.

You can use this approach to do remote scripting (aka AJAX). I will write more about using this for AJAX without using XmlHttp :), I know it would technically not be AJAX, but since AJAX is a hot word these days. It will provide a similar functionality like AJAX but it will be cross domain. That is another article that is coming soon.

Technorati Tags: ,

Comments

Patrick said…
I like the idea of a "require once" functionality where it could check if the script has been loaded already (which is great for lazy coders like me).

The following pages have similar solutions (including a way to "unload" the script which is necessary if you are writing a web app that sticks around for a while).

http://simon.incutio.com/archive/2005/12/16/json
http://www.theurer.cc/blog/2005/12/15/web-services-json-dump-your-proxy/
Anonymous said…
Note that using this function requires that the included file be fully loaded before any of the code within that file can be executed (as scripts are downloaded asynchronously). If you require the code to be executed immediately after the include statement, you can use the XMLHttpRequest object, setting the async flag to false.

Popular posts from this blog

The best mobile development platform for hobbyist programmer

Using Voicemail with Airtel Prepaid Karnataka

And yet more invites for joost