Blog>
Snippets

Implementing Lazy Loading with a Vue Plugin

Explain how to create a plugin that enables lazy loading of components or images when they are about to enter the viewport.
// Vue plugin for lazy loading components or images
Vue.use(VueLazyload, {
  // Set the options for the lazyload plugin
  lazyComponent: true,
  preLoad: 1.3,
  error: 'dist/error.png',
  loading: 'dist/loading.gif',
  attempt: 1
});
This JavaScript code snippet registers the VueLazyload plugin with Vue, configuring it with options to enable lazy loading of components and images.
<template>
  <div>
    <!-- Use v-lazy as a directive for images -->
    <img v-lazy="image.src" alt="Lazy loaded image">
    
    <!-- Lazy load a component using the v-lazy-component directive -->
    <lazy-component v-lazy-component>
      <my-component></my-component>
    </lazy-component>
  </div>
</template>
This HTML snippet demonstrates how to use the 'v-lazy' directive for images and 'v-lazy-component' directive for components within a Vue component's template.
import Vue from 'vue';
import VueLazyload from 'vue-lazyload';

// Registering the lazy load plugin with default options
Vue.use(VueLazyload);

export default {
  components: {
    // Lazy-load components must be registered locally or globally
    'lazy-component': Vue.component('lazy-component', {
      functional: true,
      render(h, { data, children }) {
        return h('div', data, children);
      }
    })
  },
  data() {
    return {
      image: {
        src: 'path/to/your/image.jpg'
      }
    };
  }
};
This JavaScript code snippet demonstrates how to import and use the VueLazyload plugin within a Vue component, registering a 'lazy-component' for lazy loading, and defining the data property for the image source.
<style>
  .vue-lazyload-loading {
    background: url('dist/loading.gif') no-repeat center;
  }
  .vue-lazyload-error {
    background: url('dist/error.png') no-repeat center;
  }
</style>
This CSS snippet provides styling for elements that are loading or have failed to load, showing a loading gif or an error image respectively.