I use dynamic script loading to reduce the duration of the initial page load. To ensure that the functions and objects defined by a script are accessible, I need to ensure that the script has been fully loaded.
I have developed my own Javascript library to this end, and thus did quite a lot of research on the subject, studying how it's done in different libraries. During a discussion related to this issue, Kyle Simpson, the author of LABjs, stated that:
LABjs (and many other loaders) set both "onload" and "onreadystatechange" on all script elements, knowing that some browsers will fire one, and some will fire the other...
You can find an example of this in the current version of jQuery as of this writing, v1.3.2:
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function(){
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
done = true;
success();
complete();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
That's the state of the art, but during the analysis of a strange behavior in Opera 9.64, I came to the conclusion that, using this technique, the onload callback got fired too early.
I will post my own findings in answer to this question, and would like to gather further evidence and feedback from the community.
.onreadystatechange
and.onload
and replaced them with promises? Clicky – Judson