我想在一个网页中检测到一些javascript或css元素加载失败,并提醒用户.我有下面的,但它不工作.
(实际的用例涉及最终用户需要安装某些证书,如果元素无法加载,页面将给出如何更新浏览器/操作系统的指令.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Lorum Title Ipsus</title>
<script>
document.addEventListener('DOMContentLoaded', (event) => {
// Monitor <script> elements
document.querySelectorAll('script[src]').forEach(script => {
script.addEventListener('error', function() {
alert('Failed to load script:', script.src);
}, true);
});
// Monitor <link rel="stylesheet"> elements
document.querySelectorAll('link[rel="stylesheet"]').forEach(link => {
link.addEventListener('error', function() {
alert('Failed to load stylesheet:', link.href);
}, true);
});
});
</script>
<!-- **** NOTE THE OBVIOUS ERROR BELOW -->
<link href="https://ERRRORcdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
</head>
<body>
Lorum Ipsus
</body>
</html>