Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 348
Chris Dutrow Avatar asked Aug 24 '12 19:08

Chris Dutrow


People also ask

How do I check if a JavaScript script is loaded?

Pass the URL of JavaScript file in a <script> tag. Set the onload parameter, Trigger alert if script loaded. If not then check for loaded variable, if it is equal to false, then script not loaded.

What is asynchronous JavaScript loading?

Synchronously, where scripts are loaded sequentially, one after another, starting with the <head> tag. Asynchronously, where some scripts can be loaded simultaneously.


1 Answers

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.

like image 146
semekh Avatar answered Sep 21 '22 13:09

semekh