我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
如果有人正在寻找一些更先进的东西,试试 RequireJS. 你会得到添加的好处,如依赖管理,更好的竞争,并避免复制(即,获得一个脚本超过一次)。
您可以将 JavaScript 文件写入“模块”,然后将其列为其他脚本中的依赖,或者您可以使用 RequireJS 作为一个简单的“去获取这个脚本”解决方案。
例子:
将依赖定义为模块:
某些依赖性.js
define(['lib/dependency1', 'lib/dependency2'], function (d1, d2) {
//Your actual script goes here.
//The dependent scripts will be fetched if necessary.
return libraryObject; //For example, jQuery object
});
implementation.js 是您的“主要” JavaScript 文件,取决于某些 dependency.js
require(['some-dependency'], function(dependency) {
//Your script goes here
//some-dependency.js is fetched.
//Then your script is executed
});
從 GitHub README 發表:
RequireJS 加载平面 JavaScript 文件以及更定义的模块. 它是优化在浏览器中的使用,包括在 Web 工作者,但它可以用于其他 JavaScript 环境,如 Rhino 和 Node. 它实施了 Asynchronous 模块 API. RequireJS 使用平面脚本标签加载模块/文件,所以它应该允许轻松的解体。
其他回答
这应该做:
xhr = new XMLHttpRequest();
xhr.open("GET", "/soap/ajax/11.0/connection.js", false);
xhr.send();
eval(xhr.responseText);
有一个好消息给你. 很快你将能够轻松地加载JavaScript代码. 它将成为进口JavaScript代码的标准方式,并将是核心JavaScript本身的一部分。
您只需要从“cond.js”中输入代码;从“cond.js”文件中加载一个名为 macro 的代码。
因此,您不需要依靠任何JavaScript框架,也不需要明确进行Ajax通话。
提到:
静态模块分辨率模块充电器
如果你想要它在纯粹的JavaScript,你可以使用document.write。
document.write('<script src="myscript.js" type="text/javascript"></script>');
如果您使用 jQuery 图书馆,您可以使用 $.getScript 方法。
$.getScript("another_script.js");
对于 Node.js 而言,这对我来说是最好的!
我在这里尝试了很多解决方案,但没有一个帮助我只是能够在没有改变范围的情况下加载另一个文件。
const fs = require('fs');
eval(fs.readFileSync('file.js') + '');
旧版本的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 加载的一般文章,讨论了这一点。
源代码合并/预处理