javascript - 使用 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);
}
解决方案
推荐阅读
- html - 单击另一个按钮时如何关闭 HTML 中的按钮,以便折叠的文本不会重叠/按钮的数据
- c++ - “collect2.exe:错误:ld 返回 1 退出状态”是我在尝试使用 c lang 时得到的
- httpclient - 带有 Angular 元素的 SPFx Webpart 在 SharePoint 页面中不起作用
- java - 使用 Firestore 数据库检索和存储用户日期的 Java 算法
- python - 用于验证特殊字符和小写字母的 if 语句
- java - 无法解析 Android 应用程序模块的 Gradle 配置。解决 Gradle 构建问题/重新同步
- c++ - 如何将简单的字符串 cpp 变量转换为 MIPS 代码
- java - 为什么在这个java程序中使用z?
- flutter - 用于链接的 Flutter markdown 自定义 BlockSyntax
- python - 从原始文本文件创建 pandas df