JavaScript 全局处理所有 img 加载错误,显示占位 base64 图片
(function () {
const base64 = "data:image/png;base64,xxxxxx";
const errorClassName = "img-load-error";
document.addEventListener(
"error",
(e) => {
let target = e.target;
const tagName = target.tagName || "";
const curTimes = Number(target.dataset.retryTimes) || 0;
if (tagName.toLowerCase() === "img") {
if (curTimes >= 3) {
target.classList.remove(errorClassName);
target.classList.add(errorClassName);
} else {
target.dataset.retryTimes = curTimes + 1;
target.src = target.src;
}
}
target = null;
},
true
);
function errorStyle() {
const style = document.createElement("style");
document.head.appendChild(style);
style.innerHTML = `
img.${errorClassName} {
display: inline-block;
transform: scale(1);
content: "";
color: transparent;
}
img.${errorClassName}::before {
content: "";
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: #f5f5f5 url(${base64}) no-repeat center / 50% 50%;
}
`;
}
window.addEventListener("load", errorStyle, { once: true });
})();