Javascript 使用脚本标记在Internet Explorer上检测xml加载失败

Javascript 使用脚本标记在Internet Explorer上检测xml加载失败,javascript,xml,internet-explorer,Javascript,Xml,Internet Explorer,是否有一种仅用于客户端的方法来检测托管在另一个域上的xml文件是否丢失(响应404)或是否可用Internet Explorer?CORS不是一个选项。我只关心它的存在 Chrome和Firefox只有一种客户端方法,它将标记注入与对“加载”和“错误”事件的回调相结合。下面是我在Firefox和Chrome浏览器控制台中放置的测试代码 在Internet Explorer中,无论文件是否存在,“readystatechange”事件始终激发。我已经检查了从“readystatechange”回调

是否有一种仅用于客户端的方法来检测托管在另一个域上的xml文件是否丢失(响应404)或是否可用Internet Explorer?CORS不是一个选项。我只关心它的存在

Chrome和Firefox只有一种客户端方法,它将
标记注入与对“加载”和“错误”事件的回调相结合。下面是我在Firefox和Chrome浏览器控制台中放置的测试代码

在Internet Explorer中,无论文件是否存在,“readystatechange”事件始终激发。我已经检查了从“readystatechange”回调返回的对象,似乎找不到现有文件的响应对象和不存在文件的响应对象之间的区别

我还尝试了
标记和
标记注入,结果对任何浏览器都不如
标记注入有用


我还没有完全测试过这个,但它可能会工作。 由于您希望加载XML,如果它确实存在并且加载到脚本中,浏览器在解析文件时将抛出
语法错误
,而如果返回404,则不会出现错误,因此您可以为IE添加以下内容

function loadFile(urlOfDocument) {
    var element = document.createElement('script');
    element.async = true;

    element.onload = function() {
        // Works for Chrome and Firefox
        console.log("onload called");
    }
    element.onerror = function() {
        // Works for Chrome and Firefox
        console.log("onerror called");
    }
    element.onreadystatechange= function () {
        // IE 8, 9, 10
        console.log("onreadystatechange: ", element.readyState);
        if (this.readyState == 'complete') {
            console.log("loading complete");
        }
    }
    element.src = urlOfDocument;
    document.getElementsByTagName('head')[0].appendChild(element);
}

var urlOfDocument = "http://url.to.missing.file";
loadFile(urlOfDocument);
注意:这对有效的脚本文件不起作用


希望这有帮助

感谢您花时间编写此解决方案,但它不起作用。readyState=='loaded'从不激发。@til2code当您记录
readyState
console.log(this.readyState)
'loading'
之后,您会得到什么?
'loaded'
(在IE8中),如果没有任何效果,您也可以使用超时。
    if (this.readyState == 'loading') {
       window.onerror = function(e){
          if(! (e === "Syntax error") ) return;
          console.log("File Exits");
          window.fileExists = true;
       }
    }
   if (this.readyState == 'loaded') {
       //if we got here without an error the file is missing. 
       if(!window.fileExists){
           console.log("File is missing");
       }
       //clean up
       window.onerror = "";
    }