我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
是的,有......
在 ES6 中,我们可以将部分或整个JavaScript文件导出并导入到另一个文件中。
但等待,ES6不支持所有浏览器,所以你需要通过 babel.js 使用它,例如...
所以你创建一个类如下:
class Person {
constructor(name) {
this.name = name;
}
build() {
return new Person(this);
}
}
module.exports = Person;
import { Person } from 'Person';
您也可以要求文件如:
const Person = require('./Person');
如果您正在使用更古老的 JavaScript 版本,您可以使用 requirejs:
requirejs(["helper/util"], function(util) {
// This function is called when scripts/helper/util.js is loaded.
// If util.js calls define(), then this function is not fired until
// util's dependencies have loaded, and the util argument will hold
// the module value for "helper/util".
});
如果你想坚持旧版本的物品,如jQuery,你也可以使用一些东西,如 getScript:
jQuery.getScript('./another-script.js', function() {
// Call back after another-script loaded
});
最后,但不要忘记,你可以用 <script> 标签一起编写脚本的传统方式。
<script src="./first-script.js"></script>
<script src="./second-script.js"></script>
<script src="./third-script.js"></script>
注意: 有几种方式可以执行一个外部脚本: 如果 async 存在: 脚本与页面剩余的同步执行(脚本将执行,而页面继续播放) 如果 async 没有存在,并且 defer 存在: 脚本在页面完成播放时执行 如果没有 async 或 defer 存在: 脚本被捕并执行 imme
其他回答
旧版本的JavaScript没有进口,包括,或要求,所以许多不同的方法对这个问题已经开发。
使用 package.json:
{
"type": "module"
}
export function hello() {
return "Hello";
}
import { hello } from './module.js';
let val = hello(); // val is "Hello";
export function hello() {
return "Hello";
}
此分類上一篇:mjs:
import { hello } from './module.mjs';
let val = hello(); // val is "Hello";
ECMAScript 在浏览器中的模块
<script type="module">
import { hello } from './hello.mjs'; // Or the extension could be just `.js`
hello('world');
</script>
// hello.mjs -- or the extension could be just `.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 需要
// mymodule.js
module.exports = {
hello: function() {
return "Hello";
}
}
// server.js
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"
您可以使用 AJAX 通话加载额外的脚本,然后使用 eval 运行它. 这是最简单的方式,但由于 JavaScript Sandbox 安全模式而仅限于您的域名。
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 图书馆在一个行中提供充电功能:
$.getScript("my_lovely_script.js", function() {
alert("Script loaded but not necessarily executed.");
});
下面是如何工作的例子:
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)
}
var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
document.body.appendChild(js);
var s = new MySuperObject();
Error : MySuperObject is undefined
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 已加载后,脚本可以运行,或者在此之前,取决于浏览器,以及您是否包含了行 script.async = false;. 有一个关于JavaScript 加载的一般文章,讨论了这一点。
源代码合并/预处理
还有 Head.js. 很容易处理:
head.load("js/jquery.min.js",
"js/jquery.someplugin.js",
"js/jquery.someplugin.css", function() {
alert("Everything is ok!");
});
正如你所看到的,它比 Require.js 更容易,而且像 jQuery 的 $.getScript 方法一样方便,它还有一些先进的功能,如条件加载、功能检测等。
不要忘了查看LAB.js!
<script type="text/javascript">
$LAB.script("jquery-1.8.3.js").wait().script("scripts/clientscript.js");
</script>
下面是Facebook如何为其微妙的Like按钮进行的一般版本:
<script> var firstScript = document.getElementsByTagName('script')[0], js = document.createElement('script'); js.src = 'https://cdnjs.cloudflare.com/ajax/libs/Snowstorm/20131208/snowstorm-min.js'; js.onload = function () { // do stuff with your dynamically loaded script snowStorm.snowColor = '#99ccff'; }; firstScript.parentNode.insertBefore(js, firstScript); </sc
如果它为Facebook工作,它会为你工作。
为什么我们正在寻找第一个脚本元素而不是头部或身体是因为一些浏览器不会创建一个如果缺乏,但我们保证有一个脚本元素 - 这个一个。
此脚本将添加 JavaScript 文件到任何其他 <script> 标签的顶部:
(function () {
var li = document.createElement('script');
li.type = 'text/javascript';
li.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
li.async = true;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(li, s);
})();