The content of this article is about how to implement delayed loading of images in js? The method code for implementing lazy loading of images in js has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
/* * 思路: * 1.获取可视窗口高(clientHeight)、各个图片的绝对距离(getPub函数)以及滚动进去的高(scrollTop) * 2.滚动进去的高(scrollTop) + 视窗口高(clientHeight)>=各个图片的绝对距离 * 3.若满足第2步的条件,就让自定义属性的内容 赋值给img的src属性; * */ /*获取当前元素到html的距离*/ function getPub(obj){ var a =0; var b = 0; while (obj){ a+=obj.offsetLeft; b+=obj.offsetTop; obj=obj.offsetParent; } return {'left':a,'top':b}; } window.onload =window.onscroll= function () { var aImage = document.getElementsByTagName('img'); var cHeight = document.documentElement.clientHeight; var sHeight = document.documentElement.scrollTop; for (var i = 0;i<aImage.length;i++){ if(cHeight+sHeight>=getPub(aImage[i]).top){//2 aImage[i].src=aImage[i].getAttribute('_src');//3 } } }
Related recommendations:
JS implements image preloading without waiting
js image delayed loading (sliding with the scroll bar) )
The above is the detailed content of How to implement lazy loading of images in js? js method code to implement lazy loading of images. For more information, please follow other related articles on the PHP Chinese website!