Note. This method no longer works with Chrome 36 . There are no direct alternatives.
Note. The answer below applies only to external scripts, i.e. to those loaded using <script src> .
In Chrome (and Safari), the "beforeload" event fires just before the resource loads. This event allows you to block the resource, so the script is never retrieved. In this case, you can determine if the loaded resource is a script, and check if you want to perform some action
This event can be used to emulate beforescriptexecute / afterscriptexecute :
document.addEventListener('beforeload', function(event) { var target = event.target; if (target.nodeName.toUpperCase() !== 'SCRIPT') return; var dispatchEvent = function(name, bubbles, cancelable) { var evt = new CustomEvent(name, { bubbles: bubbles, cancelable: cancelable }); target.dispatchEvent(evt); if (evt.defaultPrevented) { event.preventDefault(); } }; var onload = function() { cleanup(); dispatchEvent('afterscriptexecute', true, false); }; var cleanup = function() { target.removeEventListener('load', onload, true); target.removeEventListener('error', cleanup, true); } target.addEventListener('error', cleanup, true); target.addEventListener('load', onload, true); dispatchEvent('beforescriptexecute', true, true); }, true);
Sending time is not 100% identical to the original, but this is sufficient for most cases. This is a temporary line for (non-emulated) events:
beforeload Before the network request is started beforescriptexecute Before a script executes afterscriptexecute After a script executes onload After the script has executed
Here is an easy way to see that events are working as expected:
window.addEventListener('afterscriptexecute', function() { alert(window.x); }); document.head.appendChild(document.createElement('script')).src = 'data:,x=1'; document.head.appendChild(document.createElement('script')).src = 'data:,x=2';
Demo can be seen live on http://jsfiddle.net/sDaZt/