有没有办法通过响应404来检测页面上的资源?
另外,为什么浏览器api- performance.getEntriesByType(“资源”)不包含失败的资源?
发布于 2015-06-18 08:32:05
好的,使用这个函数:
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
if (http.status == 404) {
// do something
}
}
然后传递资源的URL。但这不是最好的解决方案来检查这个。让我们假设它是最简单的:)
编辑:
之后,您还可以对每种资源(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。
https://stackoverflow.com/questions/30910054
复制相似问题