我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
我来到这个问题,因为我正在寻找一个简单的方式来保持一个收藏有用的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>
但是:
雖然所有插件都落入頭標籤的方式,他們不總是通過瀏覽器,當你點擊到頁面或更新。
其他回答
与 $.getScript 和实际上任何其他解决方案需要一个呼叫回复,当加载完成时的问题是,如果你有多个文件使用它,并依赖对方,你已经没有办法知道什么时候所有的脚本被加载(一旦它们被纳入多个文件)。
文件3JS
var f3obj = "file3";
// Define other stuff
文件2JS:
var f2obj = "file2";
$.getScript("file3.js", function(){
alert(f3obj);
// Use anything defined in file3.
});
此分類上一篇: JS
$.getScript("file2.js", function(){
alert(f3obj); //This will probably fail because file3 is only guaranteed to have loaded inside the callback in file2.
alert(f2obj);
// Use anything defined in the loaded script...
});
您可以尝试使用 $.when 检查一系列丢失的对象,但现在您正在做这一点在每个文件和文件2 将被视为加载,一旦 $.when 执行,而不是当呼叫回复执行,所以文件1 仍然继续执行之前文件3 被加载,这真的仍然有相同的问题。
我喜欢延长jQuery的想法,但显然你不需要。
在呼叫document.writeln之前,它检查以确保脚本已经没有被加载,通过评估所有脚本元素。
而不是这个方法,你可以尝试修改 jQuery readyList,但这似乎是一个更糟糕的解决方案。
解决方案:
$.extend(true,
{
import_js : function(scriptpath, reAddLast)
{
if (typeof reAddLast === "undefined" || reAddLast === null)
{
reAddLast = true; // Default this value to true. It is not used by the end user, only to facilitate recursion correctly.
}
var found = false;
if (reAddLast == true) // If we are re-adding the originating script we do not care if it has already been added.
{
found = $('script').filter(function () {
return ($(this).attr('src') == scriptpath);
}).length != 0; // jQuery to check if the script already exists. (replace it with straight JavaScript if you don't like jQuery.
}
if (found == false) {
var callingScriptPath = $('script').last().attr("src"); // Get the script that is currently loading. Again this creates a limitation where this should not be used in a button, and only before document.ready.
document.writeln("<script type='text/javascript' src='" + scriptpath + "'></script>"); // Add the script to the document using writeln
if (reAddLast)
{
$.import_js(callingScriptPath, false); // Call itself with the originating script to fix the order.
throw 'Readding script to correct order: ' + scriptpath + ' < ' + callingScriptPath; // This halts execution of the originating script since it is getting reloaded. If you put a try / catch around the call to $.import_js you results will vary.
}
return true;
}
return false;
}
});
使用:
var f3obj = "file3";
// Define other stuff
$(function(){
f3obj = "file3docready";
});
文件2:
$.import_js('js/file3.js');
var f2obj = "file2";
$(function(){
f2obj = "file2docready";
});
文件1:
$.import_js('js/file2.js');
// Use objects from file2 or file3
alert(f3obj); // "file3"
alert(f2obj); // "file2"
$(function(){
// Use objects from file2 or file3 some more.
alert(f3obj); //"file3docready"
alert(f2obj); //"file2docready"
});
从丹·达斯卡莱斯库(Dan Dascalescu)的答案,从Facebook的想法中获取了一些图书馆的扩展。
(function() {
var __ = {};
this._ = function(name, callback) {
if(__[name]==undefined) {
__[name] = true;
var firstScript = document.getElementsByTagName('script')[0],
js = document.createElement('script');
js.src = name;
js.onload = callback;
firstScript.parentNode.insertBefore(js, firstScript);
}
}
})();
(new _('https://cdnjs.cloudflare.com/ajax/libs/Snowstorm/20131208/snowstorm-min.js', function() {
snowStorm.snowColor = '#99ccff';
}));
也许这里还有另一种方式!
在 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.
});
可以动态地创建一个JavaScript标签并将其添加到来自其他JavaScript代码的HTML文档中,这将加载针对JavaScript文件。
function includeJs(jsFilePath) {
var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
document.body.appendChild(js);
}
includeJs("/path/to/some/file.js");