我正在尝试从JS加载另一个JS文件(因为url可能会根据用户选择的内容而变化,并且加载两者都会导致冲突问题),然后在加载文件后立即从文件中运行一个函数。我需要运行一个函数,我不能只运行代码,因为该函数需要客户端输入。我该怎么办?
在此示例中,我没有包括动态URL部分,因为它可以工作。另外,一次没有尝试2次。我分别测试了它们。他们都没有工作。这是我尝试过的:
var url="file.js", script = document.createElement('script');
script.setAttribute('src',url);
script.setAttribute('id','option');
document.head.appendChild(script);
// code attempt 1 at loading the function:
fileInit(param1);
// code attempt 2:
document.getElementById("option").onload = fileInit(param1);
// code attempt 3:
script = document.getElementById("option");
script.onload = script.onreadystatechange = fileInit(param1);
// code attempt 4:
document.getElementById("option").addEventListener("load", fileInit(param1));
我只想加载的文件是JS(因此我可以有一个动态URL),然后在加载文件时运行文件中定义的init函数。我也不想使用jQuery。我希望代码是Vanilla JS。我知道您可以使用jQuery.getScript()。
答案 0 :(得分:1)
在两个文件中都应具有以下语句exports.__esModule = true;
,在导出文件中,应对要导出的每个事物执行此操作exports.thingToExport = thingToExport;
,然后像这样进行导入:
var file = require("path/to/file");
file.thingToExport;
编辑:此问题说明了您在打字稿中为获取此节点代码所做的工作。这在现代浏览器import functions from another js file中也适用,并且可能是重复的。