3

Is it possible to know when a script injected via document.write has finished loading?

document.write('<script src="' + url + '"><\/script>');  

This is executed on page load.

Edit:

Thanks for all the help guys, really helped point me toward the right direction. I ended up using this solution from MSDN

s = document.createElement("script");
s.src="myscript.js";
if(s.addEventListener) {
  s.addEventListener("load",callback,false);
} 
else if(s.readyState) {
  s.onreadystatechange = callback;
}
document.body.appendChild(s);
function callback() { console.log("loaded"); }
6
  • 2
    Yes, it is (add a onload event to it), but you should really avoid document.write. Commented Mar 24, 2014 at 21:59
  • 2
    Sure. Just document.write() another script directly after it. Commented Mar 24, 2014 at 22:00
  • 1
    Some versions of IE don't have an onload event for script elements. And document.write() is useful when used properly, as seems to be the case here. Commented Mar 24, 2014 at 22:01
  • Are you using a library like jQuery? Commented Mar 24, 2014 at 22:02
  • possible duplicate Commented Mar 24, 2014 at 22:08

1 Answer 1

2

Listen to the readystatechange event for IE, and the load event for other browsers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.