This article mainly introduces the use of native javascript to implement image scrolling and delayed loading functions. The ideas and methods are shared with everyone. I hope it will be helpful to everyone.
Achievement effect: when the scroll bar is pulled down, the image will not start loading until it appears in the visible area
Idea:
(1) img tag, put the real image address, Put it in the properties you set, such as lazy-src
(2) Get the height of img from the page (offset().top in JQ), the native one is:
img. getBoundingClientRect().top document.body.scrollTop||document.documentElement.scrollTop
(3) Determine whether the position where img appears is in the visible area:
is in the visible area of the browser, justTop>scrollTop&&offsetTop
//保存document在变量里,减少对document的查询 var doc = document; for(var n=0,i = this.oImg.length;n<i;n++){ //获取图片占位符图片地址 var hSrc = this.oImg[n].getAttribute(this.sHolder_src); if(hSrc){ var scrollTop = doc.body.scrollTop||doc.documentElement.scrollTop, windowHeight = doc.documentElement.clientHeight, offsetTop = this.oImg[n].getBoundingClientRect().top + scrollTop, imgHeight = this.oImg[n].clientHeight, justTop = offsetTop + imgHeight; // 判断图片是否在可见区域 if(justTop>scrollTop&&offsetTop<(scrollTop+windowHeight)){ this.isLoad(hSrc,n); } } }
The following is the detailed code:
function LGY_imgScrollLoad(option){ this.oImg = document.getElementById(option.wrapID).getElementsByTagName('img'); this.sHolder_src = option.holder_src; this.int(); } LGY_imgScrollLoad.prototype = { loadImg:function(){ //保存document在变量里,减少对document的查询 var doc = document; for(var n=0,i = this.oImg.length;n<i;n++){ //获取图片占位符图片地址 var hSrc = this.oImg[n].getAttribute(this.sHolder_src); if(hSrc){ var scrollTop = doc.body.scrollTop||doc.documentElement.scrollTop, windowHeight = doc.documentElement.clientHeight, offsetTop = this.oImg[n].getBoundingClientRect().top + scrollTop, imgHeight = this.oImg[n].clientHeight, justTop = offsetTop + imgHeight; // 判断图片是否在可见区域 if(justTop>scrollTop&&offsetTop<(scrollTop+windowHeight)){ //alert(offsetTop); this.isLoad(hSrc,n); } } } }, isLoad:function(src,n){ var src = src, n = n, o_img = new Image(), _that = this; o_img.onload = (function(n){ _that.oImg[n].setAttribute('src',src); _that.oImg[n].removeAttribute(_that.sHolder_src); })(n); o_img.src = src; }, int:function(){ this.loadImg(); var _that = this, timer = null; // 滚动:添加定时器,防止频繁调用loadImg函数 window.onscroll = function(){ clearTimeout(timer); timer = setTimeout(function(){ _that.loadImg(); },100); } } }
Rendering:
The above is the entire content of this chapter. For more related tutorials, please visit JavaScript Video Tutorial!