How to check if a download has completed asynchronously loading script loading in javascript

Using javascript to asynchronously download another javascript file.

I understand that this can be done by inserting a new script tag on the page with the src attribute set to the file url.

I also need to run some code when the script finishes loading. I used yepnope for this, and they provide β€œcallbacks” that are executed when the script has finished loading and executing.

How is this achieved?

Thanks!

+6
source share
3 answers

Most JS loaders do this by entering the <script> in the DOM and binding its onload to your provided function.

yepnope uses the same approach, and you may just notice that from its source code . The injectJs function creates a DOM element using doc.createElement , sets src and other necessary attributes using setAttribute , associates the onreadystatechange and onload with the provided callback, and finally inserts the element into the document.

+3
source

yepnope.injectJs( scriptSource [, callback ] [, elemAttributes ] [, timeout ]); Hide their website : you just run the code you need in a successful callback.

 // 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
source

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

check out the link that contains detailed information about this.

+1
source

Source: https://habr.com/ru/post/923705/


All Articles