简体   繁体   中英

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

从另一个Javascript文件中包含Javascript文件的推荐方法是什么?

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.

jQuery has getScript() function. Also note that Lazy Load mentioned above is only for images. Not for JavaScript files.

$.getScript(url, [callback]); 

How about this:

( original link )

<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.

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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM