How to know that dynamically created script tag was executed?

Kosmetika picture Kosmetika · Sep 5, 2014 · Viewed 14k times · Source

I'm creating a script tag dynamically:

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.charset = 'utf-8';
script.defer = true;
script.async = true;
script.text = 'some my javascript content here';
head.appendChild(script);

script.onload = function () {
    // this never get fired..
    debugger;
}

How to get notified when script was executed inside other code block? Maybe some event?

Answer

pherris picture pherris · Sep 5, 2014

I was able to get this to work by adding an ID to the script, then in the JS, manually firing the load event on that DOM element. Tested only in Chrome, will have issues in older IE according to MDN).

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.charset = 'utf-8';
script.id = 'testing';
script.defer = true;
script.async = true;
script.onload = function () {
    console.log('The script is loaded');
}
script.text = ["console.log('This is from the script');",
               "var script = document.getElementById('testing');",
               "var event = new UIEvent('load');",
               "script.dispatchEvent(event);"].join('');
head.appendChild(script);

Fiddle