SOURCE

console 命令行工具 X clear

                    
>
console
<!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.0">
	<title>Document</title>
	<style>
		img {
			width: 200px;
		}
	</style>
</head>

<body>
	<div id="father">
		<img class="imgs"
            data-url="https://th.bing.com/th/id/Rdf0e1dd80b438afbe6ac9d4c5642e01f?rik=WzjpYrSJL7XZqA&riu=http%3a%2f%2fp7.itc.cn%2fimages01%2f20210114%2f0892aa29ab5749e6a01f411e4f3f895a.jpeg&ehk=c3YyWHLFZHKQPiFUSWKAtRb%2bYT3sSMWX1gJORu3g8t0%3d&risl=&pid=ImgRaw"
            alt="">
        <img class="imgs"
            data-url="https://th.bing.com/th/id/R782263c8db610e53494b230a86b0a2ba?rik=pXuOOEdhFkJzwQ&riu=http%3a%2f%2fimg.acgjc.com%2fwp-content%2fuploads%2f2021%2f01%2f2efc7d144f6dde5b18c5f6072ade6f11-1024x1024.jpg&ehk=wMFrPubNS94VLicVWp7rIIOeIA5rqKxbTN7N0qd1P2M%3d&risl=&pid=ImgRaw"
            alt="">
    </div>
    <script>
        class PreLoadImage {
            constructor(imgNode) {
                // 获取真实的DOM节点
                this.imgNode = imgNode
            }
            // 操作img节点的src属性
            setSrc(imgUrl) {
                this.imgNode.src = imgUrl
            }
        }

        class ProxyImage {
            // 占位图的url地址
            static LOADING_URL = 'https://img1.baidu.com/it/u=4105776946,2723577313&fm=26&fmt=auto&gp=0.jpg'

            constructor(targetImage) {
                // 目标Image,即PreLoadImage实例
                this.targetImage = targetImage
            }

            // 该方法主要操作虚拟Image,完成加载
            setSrc(targetUrl) {
                // 真实img节点初始化时展示的是一个占位图
                this.targetImage.setSrc(ProxyImage.LOADING_URL)
                // 创建一个帮我们加载图片的虚拟Image实例
                const virtualImage = new Image()
                // 监听目标图片加载的情况,完成时再将DOM上的真实img节点的src属性设置为目标图片的url
                virtualImage.onload = () => {
                    // 为了更清楚的看效果 加了个定时器
                    setTimeout(()=>{
                        this.targetImage.setSrc(targetUrl)
                    }, 1500)
                }
                // 设置src属性,虚拟Image实例开始加载图片
                virtualImage.src = targetUrl
            }
        }
        let imgs = document.querySelectorAll('.imgs');
        Array.from(imgs).forEach(img => {
            var pre = new PreLoadImage(img)
            // 假设图片真实地址存在data-url属性上
            var url = img.getAttribute('data-url');
            // 使用代理请求url,并且设置正确的url
            var pro = new ProxyImage(pre)
            pro.setSrc(url)
        })
    </script>
</body>

</html>