圖片懶加載
演示代碼:lazyload
在這方面大名鼎鼎的jQuery插件:jquery.lazyload.js,是我們做頁面懶加載優化的首選。當然大神的源碼也很簡潔。
原理實現
本人不才,請忽略本人的粗鄙代碼(兼容性,完備性,健壯性可自行實現),重在思路。
判斷圖片是否在可視區域內
圖片加載的時機,就是圖片出現在瀏覽器的窗口可視區域內。
這里我們可以通過下面代碼來判斷圖片是否出現在了符合條件的區域內。
var doms = document.querySelectorAll('img[data-src]'); //1
var rect = doms[0].getBoundingClientRect(); //2
var viewHeight = document.documentElement.clientHeight; //3
if (rect.top < viewHeight && rect.bottom >= 0) { //4
//符合條件可加載圖片
}
這里需要說明的幾個點:
- 第二列中的
getBoundingClientRect是用來獲取一個對象的top,left,right,bottom,width,height這幾個值。 - 第三列是用來獲取dom的可視高度
- 第四列的2個判斷
rect.top < viewHeight用來判斷圖片的上邊緣距離瀏覽器下邊緣的高度rect.bottom >= 0用來判斷圖片的下邊緣距離瀏覽器的上邊緣高度
滾輪事件監聽
| 瀏覽器 | 實現方法 | 事件屬性 | 向上滾動 | 向下滾動 |
|---|---|---|---|---|
| FireFox | DOMMouseScroll | detail | -3 | 3 |
| 非FireFox | onmousewheel | wheelDelta | 120 | -120 |
完整代碼
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Zqz_loadLoad實現</title>
</head>
<body>
<div style="width: 100px;height: 1000px"></div>
<img src="圖1" data-src='./img/1.jpg' width="300px" height="300px" />
<img src="圖2" data-src='./img/2.png' width="300px" height="300px" />
<img src="圖3" data-src='./img/3.png' width="300px" height="300px" />
<img src="圖4" data-src='./img/4.png' width="300px" height="300px" />
<img src="圖5" data-src='./img/5.png' width="300px" height="300px" />
</body>
<script type="text/javascript">
window.onload = function(e) {
zlazyLoad()
}
function zlazyLoad() {
var doms = document.querySelectorAll('img[data-src]');
doms.forEach(function(node) {
var rect = node.getBoundingClientRect(),
viewHeight = document.documentElement.clientHeight;
if (node.getAttribute('data-src') === '') return;
if (rect.top < viewHeight && rect.bottom >= 0) {
console.log('show')
var src = node.getAttribute('data-src');
console.log(src)
node.setAttribute('src', src)
}
})
}
//谷歌下的滾動監聽
document.addEventListener('mousewheel', function(e) {
console.log(e.wheelDelta)
zlazyLoad();
}, false)
//火狐下的滾動監聽
document.addEventListener('DOMMouseScroll',function (e) {
console.log(e.wheelDelta)
},false)
</script>
</html>
效果:

