我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
下面是使用HTML导入的浏览器(而不是Node.js)。
首先,所有 JavaScript 类和脚本都不是.js 文件,而是.js.html 文件(.js.html 只是在 HTML 页面和完整的 JavaScript 脚本/类之间识别),在 <script> 标签中,如下:
MyClass.js.html 的内容:
<script>
class MyClass {
// Your code here..
}
</script>
然后,如果你想进口你的班级,你只需要使用HTML进口:
<link rel="import" href="relative/path/to/MyClass.js.html"/>
<script>
var myClass = new MyClass();
// Your code here..
</script>
此分類上一篇: HTML 輸入將減少
HTML 进口减少,有利于 ES6 模块,您应该使用 ES6 模块。
其他回答
旧版本的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 加载的一般文章,讨论了这一点。
源代码合并/预处理
但是,如果您需要从远程来源下载JavaScript,大多数现代浏览器可能会因为CORS或类似的东西阻止您的跨网站请求。
<script src="https://another-domain.com/example.js"></script>
它不会工作. 并做 document.createElement('script').src = '......' 也不会切断它. 相反,你可以做的是通过标准 GET 请求作为资源加载 JavaScript 代码,并这样做:
<script type="text/javascript">
var script = document.createElement('script');
script.type = 'text/javascript';
let xhr = new XMLHttpRequest();
xhr.open("GET", 'https://raw.githubusercontent.com/Torxed/slimWebSocket/master/slimWebSocket.js', true);
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
script.innerHTML = this.responseText; // <-- This one
document.head.appendChild(script);
}
}
xhr.send();
</script>
通过自己抓住内容,浏览器不会注意到恶意的意图,并允许你去做请求. 然后你添加它在 <script> 的内部HTML 而不是. 这仍然会导致浏览器(至少在Chrome中测试) 打破 / 执行脚本。
再一次,这是一个边缘案例使用案例. 您将没有背面兼容性或浏览器兼容性可能. 但有趣/有用的事情要知道。
从.mix 文件中的混合文档:
混合文件只是.js 或.css 文件与.mix. 在文件名中. 混合文件只是扩展正常风格或脚本文件的功能,并允许您进口和结合。
以下是一個.mix 檔案的例子,將多個.js 檔案組成一個:
// scripts-global.mix.js
// Plugins - Global
@import "global-plugins/headroom.js";
@import "global-plugins/retina-1.1.0.js";
@import "global-plugins/isotope.js";
@import "global-plugins/jquery.fitvids.js";
混合输出这个作为脚本-global.js 以及作为一个小型版本(脚本-global.min.js)。
注意:我不以任何方式与混合,除了使用它作为一个前端开发工具. 我遇到了这个问题,看到一个混合JavaScript文件在行动(在一个混合板)并有点混淆它(“你可以这样做吗?”我认为自己)。 然后我意识到这是一个应用程序特定的文件类型(有些令人失望,同意)。
最好使用 jQuery 方式. 要延迟已准备的事件,首先拨打 $.holdReady(真实)。
$.holdReady(true);
$.getScript("myplugin.js", function() {
$.holdReady(false);
});
也许你可以使用我在此页面上发现的这个功能 如何将JavaScript文件纳入JavaScript文件中?
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
推荐文章
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- Android Studio突然无法解析符号
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?