萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

圖片懶加載進階:data-src / src2 屬性 + jQuery 封裝

京東商城早期方案:真實圖片地址存放在自定義屬性 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'});

關鍵細節

  • 自定義屬性:HTML5 建議用 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 監聽。

copyright © 萬盛學電腦網 all rights reserved