我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
也许这里还有另一种方式!
在 Node.js 中,你可以这样做,就像下面的代码一样!
主持人JS
module.exports = {
log: function(string) {
if(console) console.log(string);
}
mylog: function(){
console.log('just for log test!');
}
}
主.js
const mylog = require('./sub');
mylog.log('Hurray, it works! :)');
mylog.mylog();
雷夫斯
HTTP://requirejs.org/docs/node.html
其他回答
我基本上做如下,创建一个新的元素,并添加它来主导:
var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);
在 jQuery 中:
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// Script is now loaded and executed.
// Put your dependent JavaScript code here.
});
下面是使用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 模块。
var s=["Hscript.js","checkRobert.js","Hscript.js"];
for(i=0;i<s.length;i++){
var script=document.createElement("script");
script.type="text/javascript";
script.src=s[i];
document.getElementsByTagName("head")[0].appendChild(script)
};
也许这里还有另一种方式!
在 Node.js 中,你可以这样做,就像下面的代码一样!
主持人JS
module.exports = {
log: function(string) {
if(console) console.log(string);
}
mylog: function(){
console.log('just for log test!');
}
}
主.js
const mylog = require('./sub');
mylog.log('Hurray, it works! :)');
mylog.mylog();
雷夫斯
HTTP://requirejs.org/docs/node.html
我来到这个问题,因为我正在寻找一个简单的方式来保持一个收藏有用的JavaScript插件。
设置一个名为“plugins.js”的文件(或 extensions.js 或任何你想要的)。 保持你的插件文件与一个主文件。
//set array to be updated when we add or remove plugin files
var pluginNames = ["lettering", "fittext", "butterjam", etc.];
//one script tag for each plugin
$.each(pluginNames, function(){
$('head').append('<script src="js/plugins/' + this + '.js"></script>');
});
手动呼叫你的头中的一个文件: <script src="js/plugins/plugins.js"></script>
但是:
雖然所有插件都落入頭標籤的方式,他們不總是通過瀏覽器,當你點擊到頁面或更新。