Categories
JavaScript Vue

Lazy Load Images in a Vue App with v-lazy-image

Spread the love

We can lazy load images in a Vue app with the v-lazy-image library.

Lazy loading images makes the image only load when it’s showing on the screen.

To install it, we can run:

npm i v-lazy-image

Once that’s done, we can register the plugin by writing:

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

Vue.use(VLazyImagePlugin);
Vue.config.productionTip = false;

new Vue({
  render: h => h(App)
}).$mount("#app");

Then we can use the VLazyImage component by writing:

<template>
  <div id="app">
    <v-lazy-image src="http://placekitten.com/200/200"/>
  </div>
</template>

<script>
import VLazyImage from "v-lazy-image";

export default {
  name: "App",
  components: {
    VLazyImage
  },
  methods: {}
};
</script>

src has the URL of the image.

We can also add a placeholder image by using the src-placeholder prop:

<template>
  <div id="app">
    <v-lazy-image
      src="http://placekitten.com/200/200"
      src-placeholder="http://placekitten.com/400/400"
    />
  </div>
</template>

<script>
import VLazyImage from "v-lazy-image";

export default {
  name: "App",
  components: {
    VLazyImage
  }
};
</script>

We can also add some styles to the component by adding styles to the v-lazy-image and v-lazy-image-loaded classes. The 2nd one is applied when the image is loaded.

For instance, we can write:

<template>
  <div id="app">
    <v-lazy-image
      src="http://placekitten.com/200/200"
      src-placeholder="http://placekitten.com/400/400"
    />
  </div>
</template>

<script>
import VLazyImage from "v-lazy-image";

export default {
  name: "App",
  components: {
    VLazyImage
  }
};
</script>

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

to add some blur effect when it’s being loaded.

We can load different images according to the screen size.

To do that, we use the srcset prop.

For instance, we can write:

<template>
  <div id="app">
    <v-lazy-image
      srcset="https://cdn.pixabay.com/photo/2020/02/25/19/16/stawberry-4879794_960_720.jpg 1x, https://cdn.pixabay.com/photo/2020/02/06/08/51/water-4823443__340.jpg 2x"
      src="http://placekitten.com/400/400"
    />
  </div>
</template>

<script>
import VLazyImage from "v-lazy-image";

export default {
  name: "App",
  components: {
    VLazyImage
  }
};
</script>

We need both the src and srcset attributes. src is for the fallback image.

v-lazy-image is used for letting us lazy load images, which means that it only loads when it’s in the viewport.

It supports responsiveness and styling.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *