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 extends the <img> tag API and applies lazy loading.

To use it, once you install it by running npm install v-lazy-image, you can add it globally to your project:

// main.js
import Vue from "vue";
import { VLazyImagePlugin } from "v-lazy-image";

Vue.use(VLazyImagePlugin);

And then is as simple to use as using an <img>:

<template>
  <v-lazy-image src="http://lorempixel.com/400/200/" />
</template>

You can even use the progressive image loading technique by setting a src-placeholder property with a tiny image (usually a small version of the image), even by applying your own transition effects using CSS:

<template>
  <v-lazy-image
    src="https://cdn-images-1.medium.com/max/1600/1*xjGrvQSXvj72W4zD6IWzfg.jpeg"
    src-placeholder="https://cdn-images-1.medium.com/max/80/1*xjGrvQSXvj72W4zD6IWzfg.jpeg"
  />
</template>

<style scoped>
  .v-lazy-image {
    filter: blur(10px);
    transition: filter 0.7s;
  }
  .v-lazy-image-loaded {
    filter: blur(0);
  }
</style>

You can checkout this demo made by @aarongarciah where you can see it in action with many different CSS effects!

Don't miss out anything about Vue, your favourite framework.

Subscribe to receive all the articles we publish in a concise format, perfect for busy devs.

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

Alex Jover Morales

Alex Jover Morales

Mar 17, 2019

Naming Webpack Chunks on Lazy Loaded Routes in Vue.js

Learn in this micro tip how you can name webpack chunks generated by lazy loaded routes

Jorge Baumann

Jorge Baumann

Apr 19, 2020

Use Web Workers in your Vue.js Components for Max Performance

Learn how to get up to 20x performance improvement of Vue.js components that rely on heavy tasks so they render and load faster

Alex Jover Morales

Alex Jover Morales

Mar 31, 2020

Sponsors

VueDose is proudly supported by its sponsors. If you enjoy it, consider supporting it to ensure the project maintainability.

Silver
StoryBlok
Learning Partner
Vue School