.jpg)
网友问题:
如何将一个 JavaScript 文件包含在另一个 JavaScript 文件中,类似于在 CSS 中?@import

网友回答:
如果有人正在寻找更高级的东西,请尝试RequireJS。您将获得额外的好处,例如依赖项管理、更好的并发性和避免重复(即多次检索脚本)。
您可以在“模块”中编写JavaScript文件,然后在其他脚本中将它们作为依赖项引用。或者你可以使用RequireJS作为一个简单的“去获取这个脚本”的解决方案。
例:
将依赖关系定义为模块:
some-dependency.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文件some-dependency.js
require(['some-dependency'], function(dependency) {
//Your script goes here
//some-dependency.js is fetched.
//Then your script is executed
});
摘自 GitHub 自述文件:
RequireJS加载普通的JavaScript文件以及更多定义的
模块。它针对浏览器内使用进行了优化,包括在 Web
Worker 中,但它可以在其他 JavaScript 环境中使用,如
Rhino 和 Node。它实现异步模块 API。RequireJS使用纯脚本标签来加载模块/文件,因此它应该
允许轻松调试。它可以简单地用于加载现有的
JavaScript文件,因此您可以将其添加到现有项目中,而无需
重写JavaScript文件。…

网友回答:
旧版本的JavaScript没有导入,包含或要求,因此已经开发了许多不同的方法来解决这个问题。
但从 2015 年 (ES6) 开始,JavaScript 就有了 ES6 模块标准,可以在 Node.js 中导入模块,大多数现代浏览器也支持这种标准。
为了与旧版浏览器兼容,可以使用 Webpack 和 Rollup 等构建工具和/或 Babel 等转译工具。
ECMAScript (ES6) 模块在 Node 中得到了支持.js从 v8.5 开始,带有标志,至少从 Node.js v13.8.0 开始就支持了这个标志。要启用“ESM”(相对于 Node.js以前的 CommonJS 风格的模块系统 [“CJS”]),您可以使用 或为文件提供扩展名。(同样,如果您默认为 ESM,则可以命名使用 Node.js 以前的 CJS 模块编写的模块。--experimental-modules"type": "module"package.json.mjs.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";
使用 ,您将拥有:.mjsmodule.mjs
export function hello() {
return "Hello";
}
然后:main.mjs
import { hello } from './module.mjs';
let val = hello(); // val is "Hello";
从 Safari 10.1、Chrome 61、Firefox 60 和 Edge 16 开始,浏览器就支持直接加载 ECMAScript 模块(不需要像 Webpack 这样的工具)。检查犬座的当前支持。无需使用 Node.js’ 扩展;浏览器完全忽略模块/脚本上的文件扩展名。.mjs
<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);
}
阅读更多内容,请访问 https://jakearchibald.com/2017/es-modules-in-browsers/
动态导入允许脚本根据需要加载其他脚本:
<script type="module">
import('hello.mjs').then(module => {
module.hello('world');
});
</script>
Read more at https://developers.google.com/web/updates/2017/11/dynamic-import
较旧的 CJS 模块样式,在 Node.js 中仍然广泛使用,是 / 系统。module.exportsrequire
// mymodule.js
module.exports = {
hello: function() {
return "Hello";
}
}
// server.js
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"
JavaScript 还有其他方法可以在不需要预处理的浏览器中包含外部 JavaScript 内容。
您可以使用 AJAX 调用加载其他脚本,然后用于运行它。这是最直接的方法,但由于 JavaScript 沙盒安全模型,它仅限于您的域。使用也为错误、黑客和安全问题打开了大门。evaleval
与动态导入一样,您可以使用 promise 通过调用加载一个或多个脚本,以使用 Fetch Inject 库控制脚本依赖项的执行顺序:fetch
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.");
});
您可以将带有脚本 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)
}
此函数将在页面的 head 部分的末尾添加一个新标记,其中属性设置为作为第一个参数提供给函数的 URL。<script>src
这两种解决方案都在 JavaScript Madness: Dynamic Script Loading 中讨论和说明。
现在,您必须了解一个大问题。这样做意味着您远程加载代码。现代 Web 浏览器将加载文件并继续执行当前脚本,因为它们异步加载所有内容以提高性能。(这适用于 jQuery 方法和手动动态脚本加载方法。
这意味着,如果您直接使用这些技巧,您将无法在要求加载新加载的代码后的下一行使用它,因为它仍将加载。
例如:包含:my_lovely_script.jsMySuperObject
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);
}
Then you write the code you want to use AFTER the script is loaded in a lambda function:
var myPrettyCode = function() {
// Here, do whatever you want
};
Then you run all that:
loadScript("my_lovely_script.js", myPrettyCode);
Note that the script may execute after the DOM has loaded, or before, depending on the browser and whether you included the line . There’s a great article on Javascript loading in general which discusses this.script.async = false;
As mentioned at the top of this answer, many developers use build/transpilation tool(s) like Parcel, Webpack, or Babel in their projects, allowing them to use upcoming JavaScript syntax, provide backward compatibility for older browsers, combine files, minify, perform code splitting etc.

网友回答:
实际上有一种方法可以异步加载 JavaScript 文件,因此您可以在加载后立即使用新加载文件中包含的函数,我认为它适用于所有浏览器。
您需要在页面的元素上使用,即:jQuery.append()<head>
$("head").append($("<script></script>").attr("src", url));
/* Note that following line of code is incorrect because it doesn't escape the
* HTML attribute src correctly and will fail if `url` contains special characters:
* $("head").append('<script src="' + url + '"></script>');
*/
但是,这种方法也存在一个问题:如果导入的JavaScript文件中发生错误,Firebug(以及Firefox错误控制台和Chrome开发人员工具)将错误地报告其位置,如果您使用Firebug跟踪JavaScript错误,这是一个大问题(我这样做)。由于某种原因,Firebug 根本不知道新加载的文件,因此如果该文件中发生错误,它会报告它发生在您的主 HTML 文件中,您将无法找到错误的真正原因。
但是,如果这对您来说不是问题,那么此方法应该有效。
我实际上已经编写了一个名为$.import_js()的jQuery插件,它使用此方法:
(function($)
{
/*
* $.import_js() helper (for JavaScript importing within JavaScript code).
*/
var import_js_imported = [];
$.extend(true,
{
import_js : function(script)
{
var found = false;
for (var i = 0; i < import_js_imported.length; i++)
if (import_js_imported[i] == script) {
found = true;
break;
}
if (found == false) {
$("head").append($('<script></script').attr('src', script));
import_js_imported.push(script);
}
}
});
})(jQuery);
因此,导入 JavaScript 所需要做的就是:
$.import_js('/path_to_project/scripts/somefunctions.js');
我还在示例中对此进行了简单的测试。
它在主 HTML 中包含一个文件,然后脚本用于导入一个名为 的附加文件,该文件定义了此函数:main.jsmain.js$.import_js()included.js
function hello()
{
alert("Hello world!");
}
在包含之后,该函数被调用,您会收到警报。included.jshello()
模板简介:该模板名称为【如何将一个 JavaScript 文件包含在另一个 JavaScript 文件中,类似于在 CSS 中?@import】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。