lazy image loading vue
Lazy Image Loading in Vue
Lazy loading is a technique that defers loading of non-critical resources at page load time. Lazy loading images can significantly reduce initial page load time and page weight, and lower the number of HTTP requests made by the browser. In Vue, there are two ways to lazy load images.
Intersection Observer API
The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport. We can use this API to detect when an image enters the viewport and load it then.
<template>
<div class="image-container">
<img v-if="isVisible" :src="imageSrc" alt="..." />
<div ref="sentinel"></div>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false,
imageSrc: "https://example.com/image.jpg"
};
},
mounted() {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
this.isVisible = true;
observer.unobserve(this.$refs.sentinel);
}
},
{ threshold: 0.5 }
);
observer.observe(this.$refs.sentinel);
}
};
</script>
- The template contains an image container and an image.
- The image is only rendered when it becomes visible in the viewport.
- The sentinel is used to detect when the image enters the viewport.
- The IntersectionObserver API is used to observe the sentinel and trigger the image load.
Vue-Lazyload
Vue-Lazyload is a plugin for Vue.js that provides image lazy loading capabilities. It is easy to use and customizable.
// Install the plugin
npm install vue-lazyload
// Use the plugin
import Vue from "vue";
import VueLazyload from "vue-lazyload";
Vue.use(VueLazyload);
// Use the directive
<template>
<div class="image-container">
<img v-lazy="imageSrc" alt="..." />
</div>
</template>
<script>
export default {
data() {
return {
imageSrc: "https://example.com/image.jpg"
};
}
};
</script>
- The Vue-Lazyload plugin is installed and used.
- The v-lazy directive is used to lazy load the image.
- The image source is set to a data property.
Lazy loading images can provide significant performance benefits for your Vue application. The Intersection Observer API and Vue-Lazyload are two ways to implement lazy loading in your Vue application.