我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
输入声明在 ECMAScript 6 中。
合成
import name from "module-name";
import { member } from "module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , [...] } from "module-name";
import name , { member [ , [...] ] } from "module-name";
import "module-name" as name;
其他回答
但是,如果您需要从远程来源下载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中测试) 打破 / 执行脚本。
再一次,这是一个边缘案例使用案例. 您将没有背面兼容性或浏览器兼容性可能. 但有趣/有用的事情要知道。
另一种方式,在我看来是更清洁的,是做一个同步的Ajax请求而不是使用一个<script>标签。
下面是使用 jQuery 的例子:
function require(script) {
$.ajax({
url: script,
dataType: "script",
async: false, // <-- This is the key
success: function () {
// all good...
},
error: function () {
throw new Error("Could not load script " + script);
}
});
}
然后你可以在你的代码中使用它,因为你通常会使用一个包括:
require("/scripts/subscript.js");
并能够在下列行中从所需脚本中呼叫一个函数:
subscript.doSomethingCool();
我有要求无同步加载一系列的JavaScript文件,最终进行呼叫回复。
// Load a JavaScript file from other JavaScript file
function loadScript(urlPack, callback) {
var url = urlPack.shift();
var subCallback;
if (urlPack.length == 0) subCallback = callback;
else subCallback = function () {
console.log("Log script: " + new Date().getTime());
loadScript(urlPack, callback);
}
// Adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
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 = subCallback;
script.onload = subCallback;
// Fire the loading
head.appendChild(script);
}
例子:
loadScript(
[
"js/DataTable/jquery.dataTables.js",
"js/DataTable/dataTables.bootstrap.js",
"js/DataTable/dataTables.buttons.min.js",
"js/DataTable/dataTables.colReorder.min.js",
"js/DataTable/dataTables.fixedHeader.min.js",
"js/DataTable/buttons.bootstrap.min.js",
"js/DataTable/buttons.colVis.min.js",
"js/DataTable/buttons.html5.min.js"
], function() { gpLoad(params); });
第二个脚本不会充电,直到第一个完全充电,因此...
结果:
此分類上一篇
与 $.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"
});
ES6 模块
是的,在脚本标签(支持)中使用 type="module" :
<script type="module" src="script.js"></script>
在一个 script.js 文件中包含另一个文件如下:
import { hello } from './module.js';
...
// alert(hello());
在“module.js”中,您必须导出您将导入的函数/类:
export function hello() {
return "Hello World";
}
這裡有一個工作例子。