我使用这段代码只在图像可见的情况下才能加载图像。然而,它似乎是缓慢的数千个图像,即使他们没有被渲染。
function getViewportHeight() {
if(window.innerHeight) {
return window.innerHeight;
}
else if(document.body && document.body.offsetHeight) {
return document.body.offsetHeight;
}
else {
return 0;
}
}
function inView(elem, nearThreshold) {
var viewportHeight = getViewportHeight();
var scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
var elemTop = elem.offset().top;
var elemHeight = elem.height();
nearThreshold = nearThreshold || 0;
if((scrollTop + viewportHeight + nearThreshold) > (elemTop + elemHeight)) {
return true;
}
return false;
}
function loadVisibleImages() {
jQuery('img[data-src]').each(function() {
if(jQuery(this).is(':visible')) {
if(inView(jQuery(this), 100)) {
this.src = jQuery(this).attr('data-src');
}
}
});
}
jQuery(window).scroll(function() {
loadVisibleImages();
});我使用此代码来呈现图像:
<img src="" data-src="http://placehold.it/400x400" alt="" width="400" height="400">一切正常,但我如何优化它呢?
发布于 2015-05-08 15:00:03
在方法inView中,您可以重新计算每个滚动位置相同的变量:
viewportHeight, scrollTop,nearThreshold and their sum您可以在滚动事件处理程序中计算它们一次,然后只将它们的和传递给inView。
发布于 2015-05-08 15:10:13
我并不比你更喜欢嵌套语句,我建议你不要嵌套这段代码,让它变得更干净(在我看来)。
函数loadVisibleImages() {jQuery(‘img数据源’).each(函数(){ if(jQuery(this).is(':visible')) { if(inView(jQuery(this),100)) { this.src =jQuery(This).attr(‘data-src’;} });}
像这样
function loadVisibleImages() {
jQuery('img[data-src]').each(function() {
if(jQuery(this).is(':visible') && inView(jQuery(this), 100)) {
this.src = jQuery(this).attr('data-src');
}
});
}本质上,它与您拥有的东西是相同的,只是它没有嵌套得那么深。
在您的inView函数中,您还可以消除最后的if语句,它将从以下内容中更改
如果((scrollTop+ viewportHeight + nearThreshold) > (elemTop + elemHeight)) {返回true;}返回false;
到这个
return (scrollTop + viewportHeight + nearThreshold) > (elemTop + elemHeight)https://codereview.stackexchange.com/questions/90150
复制相似问题