亲宝软件园·资讯

展开

页面滚动加载技术实现

从前有匹马叫代码 人气:0

场景:图片资源大,而且图片很多的页面(视频网站首页,电商首页...)

解决方案:只加载视口区域的图片,加载过的图片不会重复加载

文件目录结构:

  • demo
  1. lazy.html
  2. lazy.js
  3. load.png

代码如下:

<!-- lazy.html-->
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Lazy Load Image</title> <style> * { margin: 0; padding: 0; } </style> </head> <body> <img src="load.png" data-src="https://gss0.baidu.com/70cFfyinKgQFm2e88IuM_a/forum/w=580/sign=c008c9c3164c510faec4e21250592528/8a809e81800a19d8fb72930e3ffa828ba61e4603.jpg"/> <img src="load.png" data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic2.zhimg.com%2F50%2Fv2-49868d5db57efd450b71dd9e4732aef2_hd.jpg&refer=http%3A%2F%2Fpic2.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1617348046&t=3cd17f38deca49bf7aa737ade454cf35"/> <img src="load.png" data-src="http://pics7.baidu.com/feed/4bed2e738bd4b31c3a31d144707ac97a9f2ff877.jpeg?token=e81cf8a710b944858acb7fff0a9f124c&s=D6A409E64EB3A3FD1CF0A5230300B003"/> <img src="load.png" data-src="https://gss0.baidu.com/70cFfyinKgQFm2e88IuM_a/forum/w=580/sign=c008c9c3164c510faec4e21250592528/8a809e81800a19d8fb72930e3ffa828ba61e4603.jpg"/> <img src="load.png" data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic2.zhimg.com%2F50%2Fv2-49868d5db57efd450b71dd9e4732aef2_hd.jpg&refer=http%3A%2F%2Fpic2.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1617348046&t=3cd17f38deca49bf7aa737ade454cf35"/> <img src="load.png" data-src="http://pics7.baidu.com/feed/4bed2e738bd4b31c3a31d144707ac97a9f2ff877.jpeg?token=e81cf8a710b944858acb7fff0a9f124c&s=D6A409E64EB3A3FD1CF0A5230300B003"/> <script src="./lazy.js"></script> </body> </html>
// lazy.js
function isVisible(elem) { let coords = elem.getBoundingClientRect(); let windowHeight = document.documentElement.clientHeight; let topVisible = coords.top > 0 && coords.top < windowHeight; let bottomVisible = coords.bottom < windowHeight && windowHeight > 0; return topVisible || bottomVisible; } function showVisible() { for (let img of document.querySelectorAll('img')) { let realSrc = img.dataset.src; if (!realSrc) continue; if(isVisible(img)) { img.src = realSrc; img.dataset.src = ''; } } } showVisible(); window.addEventListener('scroll',showVisible);

这里面最主要的难点就是,如果知道图片已经出现在浏览器窗口中了。我们可以通过window 监听scroll 事件,然后通过 getBoundingClientRect 方法获取对应元素相对于浏览器窗口的距离,然后再跟 clientHeight 作比较来判断该元素是否在浏览器窗口之内。

源代码地址点这里

 

加载全部内容

相关教程
猜你喜欢
用户评论