当前位置:首页 > JavaScript

js实现图片的懒加载

2026-04-04 00:00:42JavaScript

实现原理

图片懒加载的核心原理是延迟加载非视口内的图片,当用户滚动页面时,动态将占位符替换为真实图片。通过监听滚动事件或使用Intersection Observer API判断图片是否进入可视区域。

js实现图片的懒加载

传统滚动监听方式

// 获取所有需要懒加载的图片元素
const lazyImages = document.querySelectorAll('img[data-src]');

// 滚动事件处理函数
function lazyLoad() {
  lazyImages.forEach(img => {
    if (img.getAttribute('data-loaded')) return;

    const rect = img.getBoundingClientRect();
    if (rect.top < window.innerHeight && rect.bottom > 0) {
      img.src = img.getAttribute('data-src');
      img.removeAttribute('data-src');
      img.setAttribute('data-loaded', 'true');
    }
  });
}

// 初始加载可视区域图片
lazyLoad();

// 添加滚动事件监听
window.addEventListener('scroll', lazyLoad);
window.addEventListener('resize', lazyLoad);

Intersection Observer API(推荐)

const lazyImages = document.querySelectorAll('img[data-src]');

const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.getAttribute('data-src');
      img.removeAttribute('data-src');
      observer.unobserve(img);
    }
  });
});

lazyImages.forEach(img => {
  observer.observe(img);
});

HTML结构示例

<img data-src="path/to/real-image.jpg" src="path/to/placeholder.jpg" alt="description">

性能优化建议

添加防抖函数减少scroll事件触发频率

js实现图片的懒加载

function debounce(fn, delay) {
  let timer;
  return function() {
    clearTimeout(timer);
    timer = setTimeout(fn, delay);
  };
}

window.addEventListener('scroll', debounce(lazyLoad, 200));

为未加载图片添加加载动画或占位背景

img[data-src] {
  background: #f0f0f0;
  min-height: 200px;
}

兼容性处理

对于不支持Intersection Observer的浏览器,可回退到传统方法

if ('IntersectionObserver' in window) {
  // 使用Observer API
} else {
  // 使用传统滚动监听
}

标签: 加载图片
分享给朋友:

相关文章

vue实现图片循环

vue实现图片循环

实现图片循环的基本方法 在Vue中实现图片循环通常使用v-for指令结合数组数据。以下是基础实现方式: <template> <div> <img v-fo…

vue实现预加载

vue实现预加载

vue实现预加载的方法 在Vue中实现预加载可以通过多种方式优化用户体验,以下是几种常见方法: 使用Webpack的魔法注释 通过import()语法结合Webpack的/* webpackPref…

vue实现添加图片

vue实现添加图片

使用 <input type="file"> 上传图片 通过 HTML 原生文件输入框获取用户选择的图片文件,结合 Vue 的 v-on 监听文件变化事件。 <template…

vue实现图片滚动

vue实现图片滚动

实现图片滚动的 Vue 组件 使用 Vue 实现图片滚动效果可以通过自定义组件或第三方库完成。以下是两种常见方法: 方法一:使用 CSS 动画和 Vue 动态绑定 通过 Vue 的 v-for 和…

vue实现图片加载

vue实现图片加载

Vue 实现图片加载的方法 在 Vue 中实现图片加载可以通过多种方式,以下是一些常见的方法: 使用 v-bind 绑定图片路径 通过 v-bind 动态绑定图片路径,可以灵活地加载本地或远程图片。…

js实现图片加载

js实现图片加载

使用Image对象加载图片 通过JavaScript的Image对象可以动态加载图片,适用于需要预加载或动态插入图片的场景。 const img = new Image(); img.src =…