首页 > 解决方案 > 使用 vanilla javascript 使用 parcel-bundler 解决延迟加载图像

问题描述

当“src”路径被“data-src”属性替换时,包裹似乎无法识别图像!

希望这可以帮助!

这是我的 HTML 代码: Lazy-loading HTML Markup Javsascript with intersectionObserverAPI: [Lazy-loading with intersectionObserverAPI][2] 当图像相交时,我将在“load”事件后删除惰性图像类。[CSS惰性图像类][3]

[2]:https ://i.stack.imgur.com/pf1OO.png在此处输入代码 [3]:https ://i.stack.imgur.com/nOoSZ.png

这是 JS 代码:/* 延迟加载登录和注册表单的隐藏图像 */

const imgTarget = document.querySelector(".more__itf__img");

// console.log(imgTargetsArray)

const loadingImage = (entries, observer) => {
    const [entry] = entries;
    console.log(entry);

    if (!entry.isIntersecting) return;

    // Replace image "src" attribute with "data-src" attribute.
    // Loading of images happens behind the scenes, and once its finished
    // loading that image it will emit the "load" event.
    entry.target.src = entry.target.dataset.src;
    // Listening for "load" event.
    entry.target.addEventListener("load", ()=>{
    entry.target.classList.remove("lazy-image");
   });

   observer.unobserve(entry.target);
};

const imgObserver = new IntersectionObserver(loadingImage, {
    root: null,
    threshold: 0.15,
    // loading lazy-images before reaching the threshold value.
    rootMargin: "200px",
});

if(imgTarget){
    imgObserver.observe(imgTarget);
}

HTML 标记:

<section class="more__itf aos_element">
    <img
        src="./images/blur_img.svg"
        data-src="./images/more_itf_purple.svg"
        alt="more__itf"
        class="more__itf__img lazy-image"
    />
    <h3 class="more__itf__text">more in the future...</h3>
</section>

CSS 样式:/* 延迟图像加载 */

.lazy-image {
    filter: blur(10px);
}

标签: javascriptparcel

解决方案


推荐阅读