确定何时加载从另一个脚本调用的脚本



我有一个脚本,我们称之为脚本a。当脚本a加载时,它会将另一个脚本注入文档的头部,即脚本B。脚本B是大多数重要代码所在的位置。

当脚本A被添加到宿主文档时,它看起来像这样:

<script async src="http//script-a.js" onload="doSomething();"></script>

doSomething函数中,我想从脚本B中触发一些东西。不幸的是,它还没有加载,所以发生了错误。

我正试图找到一种方法来做到这一点,使嵌入脚本a的文档尽可能简单。我该怎么做?

您可以使用类似的东西,并将脚本中的url替换为"脚本B">

document.getElementById("demo").src = "https://my-random-script.glitch.me/script.js" // put your "Script B" here
<h1>Hello World</h1>
<h2>Try to find a Hi! Alert Box</h2>
<script id="demo"></script>
它从外部脚本调用

document.getElementById("demo").src = "https://my-random-script.glitch.me/scriptb.js"
var b = "Hi!"
document.getElementById("text").innerHTML = b;
alert("Hi")
function AlertAgain() {
alert("hi") // you can't use this, because the other site is blocking all scripts once all of the alerts are over! (you also can look at the site's js)
}
<h1 id="text">Of course, load your scripts!</h1>
<script id="demo"></script>
<button onclick="AlertAgain()">Click to say hi again</button>
没有删除所有脚本的脚本的演示
var b = "Hi!"
document.getElementById("text").innerHTML = b;
alert("Hi")
function AlertAgain() {
alert("hi")
}
<h1 id="text">Of course, load your scripts!</h1>
<script id="demo"></script>
<button onclick="AlertAgain()">Click to say hi again</button>

您也可以在HTML页面上有两个不同的脚本。

最新更新