gangsthub / v-lazy-image

Lazy load images using Intersection Observer, apply progressive rendering and css animations.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

v-lazy-image

npm

A Vue.js component to lazy load an image automatically when it enters the viewport using the Intersection Observer API.

Check out the fundaments on how it's built in this Alligator.io article.

Demos

Usage

npm install v-lazy-image

Warning: You'll need to install the w3c Intersection Observer polyfill in case you're targeting a browser which doesn't support it.

You can register globally the component so it's available in all your apps:

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

Vue.use(VLazyImagePlugin);

Or use it locally in any of your components:

import VLazyImage from "v-lazy-image";

export default {
  components: {
    VLazyImage
  }
};

You must pass a src property with the link of the image:

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

That image will be loaded as soon as the image enters the viewport.

Progressive loading

You can use the src-placeholder property to define an image that is shown until the src image is loaded.

When the src image is loaded, a v-lazy-image-loaded class is added, so you can use it to perform animations. For example, a blur effect:

<template>
  <div>
    <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"
      ></v-lazy-image>
  </div>
</template>

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

You could listen to the intersect and load events for more complex animations and state handling:

<template>
  <div>
    <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"
      @intersect="..."
      @load="..."
      ></v-lazy-image>
  </div>
</template>

@jmperezperez has written about the progressive loading technique on his blog, in case you want a deeper explanation.

API

Aside from the following API, you can pass any img attribute, such as alt, and they'll be added to the rendered <img> tag.

Fields marked as (*) are required.

Props

Name Type Description
src String (*) Image src to lazy load when it intersects with the viewport
src-placeholder String If defined, it will be shown until the src image is loaded.
Useful for progressive image loading, see demo

Events

Name Description
intersect Triggered when the image intersects in the viewport
load Triggered when the lazy image defined in src is loaded

About

Lazy load images using Intersection Observer, apply progressive rendering and css animations.

License:MIT License


Languages

Language:JavaScript 100.0%