<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>小小菜鸟</title>
</head>
<body>
<img class="load_img" src="https://img0.baidu.com/it/u=4217284373,243829174&fm=253&fmt=auto&app=138&f=JPEG?w=890&h=500">
<img class="load_img" src="https://img1.baidu.com/it/">
<img class="load_img" src="https://img1.baidu.com/it/u=3726332041,3886765468&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500">
<img class="load_img" src="https://img0.baidu.com">
<img class="load_img" src="https://img1.baidu.com/it/u=3726332041,3886765468&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500">
<img src="https://img1.baidu.com/it">
<script>
//获取需要加载的img
let dom_img=document.getElementsByClassName("load_img");
debugger
/**
* 遍历imgs数组,将所有图片加载出来
*/
let img_array=[];
for (let i = 0; i < dom_img.length; i++) {
console.log(dom_img);
let imgObj = new Image(); // 创建图片对象
imgObj.src = dom_img[i].src;
imgObj.addEventListener('load', function (e) { // 这里没有考虑error,实际上要考虑
console.log("这些是加载成功出来的,不用做处理")
}, false);
imgObj.addEventListener('error', function (e) { // 考虑error
console.log("这里是加载失败的");
//渲染失败的图片
dom_img[i].src="https://img2.baidu.com/it/u=2828556289,951156698&fm=253&fmt=auto&app=138&f=JPEG?w=499&h=500";
}, false);
imgObj.addEventListener("abort", function (e) { // 考虑error
console.log("这里是加载终止");
//渲染终止的图片
dom_img[i].src="https://img2.baidu.com/it/u=2828556289,951156698&fm=253&fmt=auto&app=138&f=JPEG?w=499&h=500";
}, false);
}
</script>
</body>
</html>
js 图片预加载,失败和中断处理
最新推荐文章于 2024-07-05 16:37:04 发布