Lazy load images using v-lazy-image Vue.js component
Some time ago I wanted to apply lazy loading in images in order to load them only when they enter the viewport. Researching I found different ways to do it, but they were a bit more cumbersome than what I wanted.
I wanted something as simple as having the same <img>
tag that gets lazy loaded. That's why I created v-lazy-image, a Vue.js component that imitates the <img>
tag API and applies lazy loading.
It also makes easy for you to achieve max performance by using responsive images and applying progressive image loading effortlessly, but let me show you the most simple case.
v-lazy-image
supports Vue 3+, but it has a compatible Vue 2 version.
To use it, once you install it by running npm install v-lazy-image
, just import it like a component:
<script setup>
import VLazyImage from "v-lazy-image";
</script>
In Vue 2, import it from v-lazy-image/v2
:
import VLazyImage from "v-lazy-image/v2";
export default {
components: {
VLazyImage
}
};
And then is as simple to use as using an <img>
:
<template>
<v-lazy-image src="http://lorempixel.com/400/200/" />
</template>
# See it in action
Here's the most simple demo. It shows you how the image is lazy loaded just by using <v-lazy-image>
instead of <img>
.
You can check that works by opening the Devtools Network tab, check the Img filter and clear the output. Then, when you scroll down in the demo until the image shows, you'll see the image is loaded when it enters the viewport.
Psst! See that little bar on the left of that embed? If you scroll right you'll see the demo code
Here's what you should see in the Devtools:
# Follow up
Do you think that's too basic? Yeah, the idea was to keep it basic, but I understand you want something more advanced.
In a real project you want to achieve max performance, and for that, v-lazy-image
allows you to use responsive images as well as progressive image loading.
Check them out and see your web apps flying!
Related Articles
Listen to lifecycle hooks on third-party Vue.js components
A quick tip on how to avoid repeating a double emit call and listen to lifecycle hooks externally
Mar 17, 2019
Achieve Max Performance loading your images with v-lazy-image
Don't you know what to do to improve your web performance? Learn Progressive Image Loading, a technique used by Spotify, Medium and Netflix.
Aug 30, 2021
Use Responsive Images with v-lazy-image
Is Web Performance a priority for you? Then read this article! You'll learn how to lazy load images with srcset and picture tag using v-lazy-image.
Aug 23, 2021
Sponsors
VueDose is proudly supported by its sponsors. If you enjoy it, consider supporting it to ensure the project maintainability.