通过JavaScript检测404资源

时间:2015-06-18 08:21:20

标签: javascript performance

有没有办法通过响应404检测页面上的资源?

为什么浏览器api- performance.getEntriesByType(" resource")不包含失败的资源?

1 个答案:

答案 0 :(得分:1)

好吧,有了这个功能:

function UrlExists(url) {
        var http = new XMLHttpRequest();
        http.open('HEAD', url, false);
        http.send();
        if (http.status == 404) {
             //  do something
        }
    }

然后传递资源的网址。但这不是检查这个问题的最佳解决方案。让我们说这是最简单的:)

编辑:

你也可以为各种资源(CSS,图像......)做一个像这样的函数:

var styleSheetExists = function(name) {
    for (var i in document.styleSheets) {
        if (typeof document.styleSheets[i] == "object") {
           link = document.styleSheets[i].href;
           if (link === null) {
               continue;
           }

           if (link.indexOf(name, link.length - name.length) !== -1) {
               return true;
           }
       }
   }
   return false;
}

您可以使用:

$(document).ready(function() {
    console.log(styleSheetExists('jquery-ui.css'));
    console.log(styleSheetExists('doesnotexist.css'));
});

(功能来源:How to check for 403 and 404 errors when changing the url of a resource?

通过检查各种资源,您可以确保有关于它们的404状态。

相关问题