gpt4 book ai didi

javascript - 通过 JavaScript 检测资源的 404

转载 作者:行者123 更新时间:2023-11-30 00:27:24 25 4
gpt4 key购买 nike

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

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

最佳答案

好吧,有了这个功能:

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 状态。

关于javascript - 通过 JavaScript 检测资源的 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30910054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com