Archer
Archer

Reputation: 5147

Javascript: Detecting script load completion

I'm dynamically adding script usign:

var el = document.createElement("script");
document.getElementsByTagname("head")[0].appendChild(el);

It seems neither script.onload nor document.onreadystatechange could be used to determine the end of loading process. How should I catch dynamic script load completion?

Upvotes: 3

Views: 92

Answers (2)

DDan
DDan

Reputation: 8286

I think you want something very similar to this: Trying to fire the onload event on script tag

$body.append(yourDynamicScriptElement);
yourDynamicScriptElement.onload = function() { //...
yourDynamicScriptElement.src = script;

Upvotes: 1

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20399

The onload event needs to be attached before setting the script's src, which is what causes the script to start loading.

Example:

var el = document.createElement("script");
el.onload = function() {
    // Script is loaded
}
el.src = ...

Upvotes: 3

Related Questions