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.
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.
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.
Comments
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/