Script elements and event execution

IE9 Standards mode introduces the standards-based and interoperable load event for script elements. Previous versions of Windows Internet Explorer supported only the non-interoperable onreadystatechange event for script elements.

For compatibility with existing websites, the onreadystatechange event is still supported in IE9 mode. However, sites that register for both of these events will now have two callbacks where in previous versions of Internet Explorer there was only one.

Typically, these events are used to execute functionality at a later point so as not to block page loading. In these cases, lack of feature detection (registering for both onreadystatechange and load) can result in the callback being executed twice. This typically results in script errors or broken page functionality.

The standards-based load event is the recommended event for these scenarios and should be used whenever possible. Web developers should use feature detection to detect browsers that support the load event for script elements. In legacy versions of Internet Explorer, the script should fallback to use onreadystatechange.

The following code example demonstrates an incorrect coding pattern.

s = document.createElement("script");
s.src="readystate.js";
s.onreadystatechange = callback; //Legacy IE
s.onload = callback; //Other browsers
document.body.appendChild(s);
function callback() { console.log("loaded"); }

The following code example demonstrates the recommended pattern.

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"); }