且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态JS加载中的错误处理

更新时间:2023-12-05 08:47:28

既然没有哎呀,我死了!状态,你不能显示错误消息。



编辑:删除代码,因为我的观点是你不能这样做。使用AJAX请求,您可以检查响应,看看它是否为404,但不能使用脚本标签。



edit2:第二个想法,为什么你可以通过AJAX获取脚本,并在document.body中注入'< script type ='text / javascript>'+ responseText +'< / script>'

要检查AJAX请求是否已被炸毁,请检查XMLHTTPRequest对象的status属性。如果是404,那么这是一个404。



此外,你不应该手动做这些东西。我总是建议使用Prototype或jQuery。由于我被原型弄坏了,我不应该尝试解释如何检查请求的状态。为什么你不问这个AJAX请求在另外一个问题呢?专业人士一定会告诉你如何处理各种失败,而不只是404。


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?

Since there is no "oops I died!" state, you can't display error messages.

edit: removed the code since my point is that you can't do that. With an AJAX request you can check the response and see if it's a 404 but you can't do that with a script tag.

edit2: on second thought, why don't you fetch the script via AJAX and inject a '<script type="text/javascript">' + responseText + '</script>' inside document.body?

To check if an AJAX request has bombed, check the XMLHTTPRequest object's status property. If it's 404, well, it's a 404.

Also, you shouldn't do this stuff by hand. I always suggest using Prototype or jQuery. Since I have been spoiled by Prototype, I shouldn't try to explain how to check for the request's status. Why don't you ask how to handle AJAX requests in another question here? The pros will certainly tell you how to handle all kinds of failures, not just 404.