图片懒加载的原理

实现图片懒加载

1. 使用Vue内置的指令

<template>
  <img v-lazy="imageUrl" alt="description">
</template>

<script>
export default {
  directives: {
    lazy: {
      inserted: function (el, binding) {
        const src = binding.value;
        el.src = src;
        const observer = new IntersectionObserver((entries, observer) => {
          if (entries[0].isIntersecting) {
            el.src = src;
            observer.unobserve(el);
          }
        });
        observer.observe(el);
      }
    }
  }
}
</script>

2. 使用第三方库

<template>
  <img v-lazy="imageUrl" alt="description">
</template>

<script>
import VueLazyload from 'vue-lazyload';

Vue.use(VueLazyload);

export default {
  // ...
}
</script>

3. 使用IntersectionObserver API

IntersectionObserver API是现代浏览器提供的一个原生API,可以用来监听元素是否进入可视区域。

<template>
  <img :data-src="imageUrl" alt="description">
</template>

<script>
export default {
  mounted() {
    const observer = new IntersectionObserver((entries, observer) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const img = entry.target;
          img.src = img.dataset.src;
          observer.unobserve(img);
        }
      });
    });

    const img = this.$el.querySelector('img');
    observer.observe(img);
  }
}
</script>

优化策略

1. 图片大小优化

2. 图片预加载

<img src="placeholder.png" data-src="actual-image.jpg" alt="description">

3. 使用CDN

总结