Lazy load images with v-lazy-image

#Vue#Web Performance

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!

Remember you can read this tip online (with copy/pasteable code), and don’t forget to share VueDose with your colleagues, so they also know about these tips as well!

Do you want to sponsor a VueDose tip? Send an email to info@vuedose.tips and have more info!

Start saving time and get a tip about the Vue ecosystem every week, right in your inbox.