What is the recommended way of including a Javascript file from another Javascript file?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With