How to check if an asynchronously loaded script has finished loading in javascript

白昼怎懂夜的黑 提交于 2019-12-07 03:43:44

问题


Using javascript to asynchronously download another javascript file.

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.

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.

How is this accomplished?

Thanks!


回答1:


Most JS loaders do this via injecting an <script> tag to the DOM, and binding its onload event to your provided function.

yepnope uses the same approach, and you may simply observe that from its source code. 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.




回答2:


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);



回答3:


this can be done using jquery, if u want to use it, Jquery.getScript()

checkout the link it gives detail information about it.



来源:https://stackoverflow.com/questions/12115676/how-to-check-if-an-asynchronously-loaded-script-has-finished-loading-in-javascri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!