[英]How to check if an asynchronously loaded script has finished loading in javascript
Using javascript to asynchronously download another javascript file. 使用javascript异步下载另一个javascript文件。
I understand that this can be done by inserting a new script tag onto the page with the src
attribute set to the file url. 我知道这可以通过在页面上插入新的脚本标记并将
src
属性设置为文件URL来完成。
I also need to run some code when the script is finished downloading. 我还需要在脚本下载完成后运行一些代码。 I've been using yepnope for this and they provide "callbacks" that execute when the script has finished downloading and executing.
我一直在使用yepnope ,它们提供了在脚本完成下载和执行时执行的“回调”。
How is this accomplished? 这是如何完成的?
Thanks! 谢谢!
Most JS loaders do this via injecting an <script>
tag to the DOM, and binding its onload
event to your provided function. 大多数JS加载器通过向DOM注入
<script>
标记并将其onload
事件绑定到您提供的函数来实现此目的。
yepnope
uses the same approach, and you may simply observe that from its source code . yepnope
使用相同的方法,你可以简单地从它的源代码中观察它。 The function injectJs
creates a DOM element using doc.createElement
, sets src
and other needed attributes using setAttribute
, binds the onreadystatechange
& onload
event to the provided callback, and finally inserts the element into the document. 功能
injectJs
创建使用DOM元素doc.createElement
,设置src
使用和其他所需的属性setAttribute
,结合onreadystatechange
& onload
事件所提供的回调,最后插入元件到文档中。
yepnope.injectJs( scriptSource [, callback ] [, elemAttributes ] [, timeout ]);
Straight off their website : You simply run the code you need to in the successful callback like so. 直接离开他们的网站 :你只需在成功的回调中运行你需要的代码就像这样。
// Example
yepnope.injectJs("jquery.js", function () {
console.log("It is finished loading and I can do whatever I need to here");
}, { charset: "utf-8" }, 5000);
this can be done using jquery, if u want to use it, Jquery.getScript() 这可以使用jquery完成,如果你想使用它, Jquery.getScript()
checkout the link it gives detail information about it. 结帐链接,提供有关它的详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.