Implementation effect: When the scrollbar is pulled down, the image appears in the visible area and starts loading
Ideas:
(1) Img tag, put the real image address in the properties you set, such as lazy-src
(2) Get the height of img from the page (in JQ, offset().top), natively:
img.getBoundingClientRect().top + document.body.scrollTop||document.documentElement.scrollTop
(3) Determine whether the location where the img appears is in the visible area:
.In the visible area of the browser, justTop>scrollTop&&offsetTop<(scrollTop+windowHeight), here justTop is the offsetTop+image height of the image
The code copy is as follows:
//Save document in variables to reduce query to document
var doc = document;
for(var n=0,i = this.oImg.length;n<i;n++){
//Get the image placeholder image address
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;
// Determine whether the picture is in the visible area
if(justTop>scrollTop&&offsetTop<(scrollTop+windowHeight)){
this.isLoad(hSrc,n);
}
}
}
The following is the detailed code:
The code copy is as follows:
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(){
//Save document in variables to reduce query to document
var doc = document;
for(var n=0,i = this.oImg.length;n<i;n++){
//Get the image placeholder image address
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;
// Determine whether the picture is in the visible area
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;
// Scroll: Add a timer to prevent frequent calls to loadImg function
window.onscroll = function(){
clearTimeout(timer);
timer = setTimeout(function(){
_that.loadImg();
},100);
}
}
}
Reproduction image:
The above is all about this article. The implementation effect is no worse than that of the jQuery plug-in. The code is simpler. Please refer to it.