what is the recommended way of including a Javscript file from another Javascript file?
How about this:
<script type="text/javascript">
// Function to allow one JavaScript file to be included by another.
// Copyright (C) 2006-08 www.cryer.co.uk
function IncludeJavaScript(jsFile)
{
document.write('<script type="text/javascript" src="'
+ jsFile + '"></scr' + 'ipt>');
}
</script>
and then to include a second JavaScript file simply add the line:
IncludeJavaScript('secondJS.js');
The page that came from includes some gotchas that arise from this approach, so it's worth looking at before using the method.
There are libraries that'll do this for you. You can also add a script tag to your document pointing to the file you want to load (from js), which is simplest, but has problems.
http://developer.yahoo.com/yui/yuiloader/
http://www.appelsiini.net/projects/lazyload
Edit: I see a lot of answers that add a script tag to the head of your document. As I said this simple solution has a problem, namely you won't know when the browser has finished loading the script you requested, so you wont know when you can call this code. If you want to use a solution like this you should also add a callback somehow to tell you when the required code was loaded.
Most people add the JavaScript file to the head of the document:
<script type="text/javascript">
var newfile=document.createElement('script');
newfile.setAttribute("type","text/javascript");
newfile.setAttribute("src", '/myscript.js');
document.getElementsByTagName("head")[0].appendChild(newfile);
</script>
Theres also an function built into Scriptaculous that is very easy to use.
Scriptaculous.require("path/to/script.js");
Worth knowing, since Scriptaculous is a very common javascript library these days.
jQuery has getScript() function. Also note that Lazy Load mentioned above is only for images. Not for JavaScript files.
$.getScript(url, [callback]);
Dojo does it using dojo.require()
:
dojo.require("your.module.name");
Normally this is a synchronous operation done with XHR. But if you use the xDomain build it will be asynchronous and dojo.addOnLoad()
will be raised when the script is loaded.
Read more about it:
- Modules
- What dojo.require does
- Quickstart: custom builds (includes xDomain explanation)
- Cross-domain Dojo (specifically dedicated to xDomain stuff).