Andrew
Andrew

Reputation: 43

Question about when a script is executed after appending it

In my code, I have javascript that dynamically adds another script to the page:

created_script=document.createElement('script');
created_script.src='other_script';
created_script.type='text/javascript';
document.head.appendChild(created_script);

in this 'other script', I have a function called reloader().

The problem I'm having is that right after I dynamically add the script, I try to call the function reloader(), but I'm getting a reloader is not defined error. Here's is like what I am doing:

created_script=document.createElement('script');
created_script.src='other_script';
created_script.type='text/javascript';
document.head.appendChild(created_script);
reloader();

Can someone explain to me why this doesn't work and how should I fix this so that reloader() can be called after appending the script in a single dynamic call (if possible at all)?

Upvotes: 1

Views: 134

Answers (1)

harto
harto

Reputation: 90503

Loading scripts like this happens asynchronously. This means that at the time you call reloader(), the external script may still be loading.

Your script shouldn't invoke loader() until it knows that the external script has completely loaded. See this related question: How can I delay running some JS code until ALL of my asynchronous JS files downloaded?

Upvotes: 2

Related Questions