京東商城早期方案:真實圖片地址存放在自定義屬性 src2(或 data-src),進入視口時賦給 src 觸發加載。
$.fn.lazyload = function(opt){
const cfg = $.extend({defObj: null, defHeight: 0}, opt);
const $imgs = (typeof cfg.defObj === 'object') ? cfg.defObj.find('img') : $(cfg.defObj).find('img');
const viewportBottom = () =>
document.documentElement.clientHeight + Math.max(document.documentElement.scrollTop, document.body.scrollTop) - cfg.defHeight;
const check = () => {
$imgs.each(function(){
const $this = $(this);
if($this.offset().top <= viewportBottom()){
const src2 = $this.attr('src2');
if(src2){
$this.attr('src', src2).removeAttr('src2'); // 只加載一次
}
}
});
};
check();
$(window).on('scroll', check);
};
// 用法
$('.container').lazyload({defObj: '.w1'});
data-src,避免無效屬性警告。removeAttr('src2') 防止重複請求。requestAnimationFrame 或 lodash.throttle 包裝 check。<img data-src="real.jpg" class="lazy" alt="...">
<script>
new IntersectionObserver((entries, obs) => {
entries.forEach(en => {
if(en.isIntersecting){
const img = en.target;
img.src = img.dataset.src;
img.classList.remove('lazy');
obs.unobserve(img);
}
});
}).observe(document.querySelectorAll('.lazy'));
</script>
原生 IntersectionObserver 無依賴、高性能、自動處理滾動/縮放,強烈推薦替代 scroll 監聽。