我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
保持它好,短,简单,可持续的! :]
// Third-party plugins / script (don't forget the full path is necessary)
var FULL_PATH = '', s =
[
FULL_PATH + 'plugins/script.js' // Script example
FULL_PATH + 'plugins/jquery.1.2.js', // jQuery Library
FULL_PATH + 'plugins/crypto-js/hmac-sha1.js', // CryptoJS
FULL_PATH + 'plugins/crypto-js/enc-base64-min.js' // CryptoJS
];
function load(url)
{
var ajax = new XMLHttpRequest();
ajax.open('GET', url, false);
ajax.onreadystatechange = function ()
{
var script = ajax.response || ajax.responseText;
if (ajax.readyState === 4)
{
switch(ajax.status)
{
case 200:
eval.apply( window, [script] );
console.log("library loaded: ", url);
break;
default:
console.log("ERROR: library not loaded: ", url);
}
}
};
ajax.send(null);
}
// Initialize a single load
load('plugins/script.js');
// Initialize a full load of scripts
if (s.length > 0)
{
for (i = 0; i < s.length; i++)
{
load(s[i]);
}
}
这个代码只是一个短暂的功能例子,可能需要额外的功能功能,以便在任何(或提供)平台上提供完整的支持。
其他回答
也许这里还有另一种方式!
在 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
在现代语言中,如果脚本已经加载了,则会:
function loadJs( url ){
return new Promise(( resolve, reject ) => {
if (document.querySelector( `head > script[ src = "${url}" ]`) !== null ){
console.warn( `script already loaded: ${url}` );
resolve();
}
const script = document.createElement( "script" );
script.src = url;
script.onload = resolve;
script.onerror = function( reason ){
// This can be useful for your error-handling code
reason.message = `error trying to load script ${url}`;
reject( reason );
};
document.head.appendChild( script );
});
}
使用(async/await):
try { await loadJs("https://.../script.js"); }
catch(error) { console.log(error); }
或
await loadJs( "https://.../script.js" ).catch( err => {} );
使用(承诺):
loadJs( "https://.../script.js" ).then( res => {} ).catch( err => {} );
如果您使用 Angular,那么一个插件模块 $ocLazyLoad 可以帮助您做到这一点。
以下是其文档的一些引用:
加载一个或多个模块和组件有多个文件: $ocLazyLoad.load([‘testModule.js’,‘testModuleCtrl.js’,‘testModuleService.js’]);加载一个或多个模块有多个文件,并在需要时指定一个类型: 注意: 使用需要JS 风格格格格式(例如,从 js! 开始时),不要指定一个文件扩展。
你不能进口,但你可以参考。
PhpShtorm IDE. 要提到,在一个.js 文件到另一个.js,只需将此添加到文件的顶部:
<reference path="../js/file.js" />
当然,你应该使用自己的PATH到JavaScript文件。
我不知道它是否会在其他IDES中工作,也许是的,只是试试,它也应该在Visual Studio中工作。
上面的功能工作顺利,如果您只加载一个脚本,或者您不关心多个脚本的加载顺序. 如果您有某些脚本依赖于其他,您需要使用承诺来指定加载顺序. 背后的原因是JavaScript加载资源如脚本和图像无同步。
因此,这里是另一个动态LoadScript的版本,保证下载命令:
// Based on: https://javascript.info/promise-basics#example-loadscript
function dynamicallyLoadScript(url) {
return new Promise(function(resolve, reject) {
var script = document.createElement("script");
script.src = url;
script.onload = resolve;
script.onerror = () => reject(new Error(`Error when loading ${url}!`));
document.body.appendChild(script);
});
}
dynamicallyLoadScript("script1.js")
.then(() => dynamicallyLoadScript("script2.js"))
.then(() => dynamicallyLoadScript("script3.js"))
.then(() => dynamicallyLoadScript("script4.js"))
.then(() => dynamicallyLoadScript("script5.js"))
//...
现在,脚本按 script1.js、 script2.js、 script3.js 等顺序加载。
dynamicallyLoadScript("script1.js")
.then(() => dynamicallyLoadScript("script2.js"))
.then(() => foo()) // foo can be a function defined in either script1, script2
.then(() => dynamicallyLoadScript("script3.js"))
.then(() => {
if (var1){ // var1 can be a global variable defined in either script1, script2, or script3
bar(var1); // bar can be a function defined in either script1, script2, or script3
} else {
foo(var1);
}
})
//more .then chains...
要显示未经处理的承诺拒绝(错误加载脚本等),将此未经处理的拒绝事件听器放在代码的顶部:
// Based on: https://javascript.info/promise-error-handling#unhandled-rejections
window.addEventListener('unhandledrejection', function(event) {
// the event object has two special properties:
console.error(event.promise);// the promise that generated the error
console.error(event.reason); // the unhandled error object
});
短短功能
function dynamicallyLoadScripts(urls) {
if (urls.length === 0)
return;
let promise = dynamicallyLoadScript(urls[0]);
urls.slice(1).forEach(url => {
promise = promise.then(() => dynamicallyLoadScript(url));
});
}
要使用它,只需通过一系列脚本URL如下:
const scriptURLs = ["dist/script1.js", "dist/script2.js", "dist/script3.js"];
dynamicallyLoadScripts(scriptURLs);