I am loading a JS file needed only for one part of my web page, only when the user navigates to that tab on the page.
var scriptFile = document.createElement("script");
scriptFile.setAttribute("type", "text/javascript");
scriptFile.setAttribute("src", scriptURL);
I am trying to come up with an error handling mechanism for this dynamic loading, so that I can show an error message if the JS load times out or if the JS is unavailable in the location specified by the URL.
This is how I am trying to implement the error handling (for IE):
scriptFile.onreadystatechange = function() { // For IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
// Display content in tab
} else {
// Display error message
}
}
This is causing one problem. When all is fine, and the JS is present as expected, I am getting the error message first, and then the correct content.
After some brainstorming, I found out that the readyState changes from "uninitialized" to "loading" first, and then to "loaded". Its when the state is at "loading" that the error message is being displayed. After that, the state is changing to "loaded" at which point the content is being displayed.
Any ideas how to handle this so the error is not displayed initially?