Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way of including a JS file from JS code?

Tags:

javascript

What is the recommended way of including a Javascript file from another Javascript file?

like image 915
Shameem Avatar asked Dec 23 '08 07:12

Shameem


2 Answers

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>
like image 153
Ryan Doherty Avatar answered Nov 07 '22 15:11

Ryan Doherty


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.

like image 23
Vasil Avatar answered Nov 07 '22 13:11

Vasil