views:

52

answers:

3

Hi friends, what are all the different ways to include an external javascript file into a html? Please give me some examples.

Thanks in advance.

+4  A: 

Three possible solutions

Standard Way

<script type="text/javascript" language="javascript" src="myfile.js"></script>

Via Javascript itself (example)

function loadCoolScript(){
  var file=document.createElement('script')
  file.setAttribute("type","text/javascript")
  file.setAttribute("src", "http://siteb.com/cool-script-location/cool-script.js")
  document.getElementsByTagName("head")[0].appendChild(file)
}

Non Blocking Loading via LabJS

<script>
   $LAB
   .script("framework.js").wait()
   .script("plugin.framework.js")
   .script("myplugin.framework.js").wait()
   .script("init.js");
</script>
Henrik P. Hessel
If you use JQuery: `$.getScript('path_to_file.js')` http://api.jquery.com/jQuery.getScript
gertas
A: 

You can include external JavaScript files anywhere on your page by adding a <script> tag:

<script type="text/javascript" src="yourJavaScriptFile.js"></script>

If possible, it's useful to add this part just above the closing <body> tag. Otherwise it would slow down the loading of other parts, visible to the user.

Be careful, if you have a script call in the html source, (e.g.: <div onclick="functionFromExternalJavaScriptFile()"> this will not work until the JavaScript file is loaded, even though the user could click on that div already. That would trigger a JavaScript error.

To be sure that could not happen, you have to load the script file above that tag.

There are some workarounds to be sure not to trigger an error, but I can't some examples, right now :-(

Jan
That's ok, but you're not limited to the <head> section of your page. It's common to put these just before closing the <body> section, so your page loads faster. This will depend on what you do with javascript.
sabanito
This does not need to be in the <head> section. In fact, it is more often faster to put it at the end of the <body> since it is a blocking load.
Hogan
A: 

Here are three different ways...

1. <script src="js/master.js" type="text/javascript"/>
2. function include(file) {
 var script = document.createElement('script');
 script.src = file; script.type = 'text/javascript';
 script.defer = true;
 document.getElementsByTagName('head').item(0).appendChild(script);
 } 

/* include any js files here */ include('js/myFile1.js'); include('js/myFile2.js');
3.document.write('<script src='myjs' />');
sushil bharwani
The third option won't work for XHTML documents loaded in XML mode.
gertas