标签:add 进入 users tar char select meta rip attr
所谓懒加载就是在图片进入 *可视区域* 前,用 *同一张* 图片作为图片的 src 属性值,这样可减少请求及带宽。懒加载的重点是:判断元素是否进入可视区域?
元素距离文档顶部高度(这个值固定不变) - 整个文档被滚动高度(浏览器滚动条向下滚动高度) <= 可视高度,表示元素进入可视区域
Demo:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>懒加载</title> <style type="text/css"> * { padding: 0; margin:0; } img { display: block; height: 171px;} </style> </head> <body> <img src="../site/images/users_avatar/user1.png" data-loaded="1"> <img src="../site/images/users_avatar/user2.png" data-loaded="1"> <img src="../site/images/users_avatar/user3.png" data-loaded="1"> <img src="../site/images/users_avatar/user4.png" data-loaded="1"> <img src="../site/images/users_avatar/user5.png" data-loaded="1"> <img src="../site/images/loading-1.gif" data-loaded="0"> <img src="../site/images/loading-1.gif" data-loaded="0"> <img src="../site/images/loading-1.gif" data-loaded="0"> <img src="../site/images/loading-1.gif" data-loaded="0"> <img src="../site/images/loading-1.gif" data-loaded="0"> <img src="../site/images/loading-1.gif" data-loaded="0"> <img src="../site/images/loading-1.gif" data-loaded="0"> <img src="../site/images/loading-1.gif" data-loaded="0"> <img src="../site/images/loading-1.gif" data-loaded="0"> <img src="../site/images/loading-1.gif" data-loaded="0"> <img src="../site/images/loading-1.gif" data-loaded="0"> </body> <script type="text/javascript"> window.onload = function () { window.onscroll = function () { // 重点:判断元素是否进入可视区域? // 元素距离文档顶部高度(这个值固定不变)减去 // 整个文档被滚动高度(浏览器滚动条向下滚动高度) // 小于等于可视高度,表示元素进入可视区域 var images = document.querySelectorAll(‘img‘); var scroll_h = document.documentElement.scrollTop; var visual_h = window.innerHeight; // 实现等待加载效果 setTimeout(function() { for (var i = 5; i < images.length; i++) { if (images[i].getAttribute(‘data-loaded‘) === ‘0‘ && images[i].offsetTop - scroll_h <= visual_h ) { images[i].src = "../site/images/users_avatar/user" + (i + 1) + ".png"; images[i].setAttribute(‘data-loaded‘, ‘1‘); } } }, 550); } } </script> </html>
标签:add 进入 users tar char select meta rip attr
原文地址:https://www.cnblogs.com/gentsir/p/12771005.html