Javascript的旧版本没有导入,包含或要求,因此已经开发了许多解决此问题的方法。
但是自2015年(ES6)起,Javascript有了ES6模块标准即可在Node.js中导入模块,大多数现代浏览器也支持该模块。
为了与旧浏览器的兼容性,这样的构建工具的WebPack和汇总和/或transpilation工具,如巴贝尔都可以使用。
ES6模块
从v8.5开始,带有标志的Node.js支持
ECMAscript(ES6)模块
--experimental-modules,并且至少从不带有标志的Node.js v13.8.0
开始支持 ECMAscript(ES6)模块。要启用“
ESM”(相对于Node.js先前的CommonJS样式的模块系统[“ CJS”]),您可以
"type":"module"在中使用
package.json或为文件提供扩展名
.mjs。(类似地,
.cjs如果您的默认值为ESM,则可以命名用Node.js的先前CJS模块编写的模块。)
使用
package.json:
{ "type": "module"}然后
module.js:
export function hello() { return "Hello";}然后
main.js:
import { hello } from './module.js';let val = hello(); // val is "Hello";使用
.mjs,您将拥有
module.mjs:
export function hello() { return "Hello";}然后
main.mjs:
import { hello } from './module.mjs';let val = hello(); // val is "Hello";浏览器中的ECMAscript模块
自Safari 10.1,Chrome
61,Firefox 60和Edge
16开始,浏览器已经支持直接加载ECMAscript模块(不需要像Webpack这样的工具)。请在caniuse上查看当前支持。无需使用Node.js
.mjs扩展名;浏览器完全忽略模块/脚本上的文件扩展名。
<script type="module"> import { hello } from './hello.mjs'; // Or it could be simply `hello.js` hello('world');</script>// hello.mjs -- or it could be simply `hello.js`export function hello(text) { const div = document.createElement('div'); div.textContent = `Hello ${text}`; document.body.appendChild(div);}浏览器中的动态导入
动态导入使脚本可以根据需要加载其他脚本:
<script type="module"> import('hello.mjs').then(module => { module.hello('world'); });</script>Node.js要求
module.exports/
require系统是仍在Node.js中广泛使用的较早的CJS模块样式。
// mymodule.jsmodule.exports = { hello: function() { return "Hello"; }}// server.jsconst myModule = require('./mymodule');let val = myModule.hello(); // val is "Hello"Javascript还有其他方法可以在不需要预处理的浏览器中包含外部Javascript内容。
AJAX加载
您可以使用AJAX调用加载其他脚本,然后用于
eval运行它。这是最直接的方法,但是由于Javascript沙箱安全模型,它仅限于您的域。使用
eval还打开了漏洞,黑客和安全问题的大门。
获取加载
像动态导入一样,您可以
fetch使用承诺通过调用来加载一个或多个脚本,以使用Fetch
Inject库控制对脚本依赖项的执行顺序:
fetchInject([ 'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js']).then(() => { console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)})jQuery加载
在jQuery的库提供加载功能在同一行:
$.getscript("my_lovely_script.js", function() { alert("script loaded but not necessarily executed.");});动态脚本加载
您可以将带有脚本URL的脚本标签添加到HTML中。为了避免jQuery的开销,这是一个理想的解决方案。
该脚本甚至可以驻留在其他服务器上。此外,浏览器会评估代码。该
<script>标签可以被注入或者网页
<head>,或者只是收盘前插入
</body>标签。
这是一个如何工作的示例:
function dynamicallyLoadscript(url) { var script = document.createElement("script"); // create a script DOM node script.src = url; // set its src to the provided URL document.head.appendChild(script); // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)}此函数将
<script>在页面头部的末尾添加一个新标签,该
src属性设置为URL,该URL作为第一个参数提供给该函数。
《Javascript Madness:动态脚本加载》中讨论和说明了这两种解决方案。
检测何时执行脚本
现在,您必须知道一个大问题。这样做意味着 您需要远程加载代码
。现代的Web浏览器将加载文件并继续执行当前脚本,因为它们异步加载所有内容以提高性能。(这适用于jQuery方法和手动动态脚本加载方法。)
这意味着,如果您直接使用这些技巧, 那么在您要求加载新代码后 , 将无法在下一行使用新加载的代码 ,因为它仍将加载。
例如:
my_lovely_script.jscontains
MySuperObject:
var js = document.createElement("script");js.type = "text/javascript";js.src = jsFilePath;document.body.appendChild(js);var s = new MySuperObject();Error : MySuperObject is undefined然后,您重新加载命中的页面
F5。而且有效!令人困惑…
那么该怎么办呢?
好吧,您可以使用作者在我给您的链接中建议的技巧。总而言之,对于有急事的人,他在加载脚本时使用事件来运行回调函数。因此,您可以将所有使用远程库的代码放入回调函数中。例如:
function loadscript(url, callback){ // Adding the script tag to the head as suggested before var head = document.head; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; // Then bind the event to the callback function. // There are several events for cross browser compatibility. script.onreadystatechange = callback; script.onload = callback; // Fire the loading head.appendChild(script);}然后,在脚本加载到lambda函数中之后,编写要使用的代码:
var myPrettyCode = function() { // Here, do whatever you want};然后运行所有这些:
loadscript("my_lovely_script.js", myPrettyCode);请注意,脚本可能在加载DOM之后或之前执行,具体取决于浏览器以及是否包含line
script.async =false;。总的来说,有一篇很棒的关于Javascript加载的文章对此进行了讨论。



