开发者

what are all the different ways to include an external javascript file into a html?

what are all the different ways to include an external javascript file into a html? Please give me some examples开发者_开发技巧.

Thanks in advance.


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>


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' />');


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 :-(

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜