Webサイトに多くの画像を配置すると、初期表示の読み込みが遅くなりユーザー体験が低下します。そこで有効なのが、画像を必要なタイミングで読み込む「遅延読み込み(Lazy Loading)」です。本記事では、Vue.jsとIntersection Observer APIを使ってシンプルにLazy Loadingを実装する方法を紹介します。
Intersection Observerとは
Intersection Observer APIは、要素がビューポート(画面の表示領域)に入ったかどうかを監視できるブラウザAPIです。これを使えば、スクロール位置に応じて画像読み込み処理を発火できます。
実装手順
1. コンポーネントの作成
遅延読み込み用のカスタムコンポーネントを作成します。
<template>
<img :src="observerTriggered ? src : placeholder" :alt="alt" />
</template>
<script>
export default {
props: {
src: { type: String, required: true },
alt: { type: String, default: '' },
placeholder: { type: String, default: 'placeholder.jpg' }
},
data() {
return {
observerTriggered: false
};
},
mounted() {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
this.observerTriggered = true;
observer.disconnect();
}
});
observer.observe(this.$el);
}
};
</script>
2. 使い方
作成したコンポーネントを使い、画像を表示します。画像はビューポートに入った時点で読み込まれます。
<template>
<div>
<LazyImage
src="https://example.com/sample.jpg"
alt="サンプル画像"
placeholder="https://example.com/placeholder.jpg"
/>
</div>
</template>
<script>
import LazyImage from './LazyImage.vue';
export default {
components: { LazyImage }
};
</script>
メリット
- 初期読み込みの軽量化による表示速度向上
- スクロールに応じた無駄のないリソース読み込み
- ネイティブLazy Loading(
loading="lazy"
)より細かい制御が可能
まとめ
Vue.jsとIntersection Observerを組み合わせることで、シンプルかつ効率的な画像の遅延読み込みが実装できます。特に画像が多いページや無限スクロール型のサイトでは、パフォーマンス改善に大きく貢献します。