1

I have a script which load a javascript file run-time or async

var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'file.js';
s.onreadystatechange = function(){
    console.log(this.readyState)
};
s.onload = function(){
    console.log('onload')
};
body.appendChild(s);

The problem is that when s.onload is triggered and onload is printed in the console the script isn't loaded completely and when calling a function from the file undefined is returned

If a setTimeout is setup after the script is onload it works, but that isn't good practice

Have made some research on the topic and found the onreadystatechange event.. But the event is never triggered in my code?!

How to add an event which is triggered when the script is completely loaded?

0

1 Answer 1

2

The order is important. Append the element first and add the src last:

var s = document.createElement('script');
s.type = 'text/javascript';

body.appendChild(s);

s.onreadystatechange = function(){
    console.log(this.readyState)
};
s.onload = function(){
    console.log('onload')
};

s.src = 'file.js';
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.