• Stars
    star
    7,967
  • Rank 4,532 (Top 0.1 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Vue.js plugin for lazyload your Image or Component in your application.

Vue-Lazyload

Build Status npm version npm downloads npm license PRs Welcome CDNJS version

Vue module for lazyloading images in your applications. Some of goals of this project worth noting include:

  • Be lightweight, powerful and easy to use
  • Work on any image type
  • Add loading class while image is loading
  • Supports both of Vue 1.0 and Vue 2.0

For Vue 3

Please use [email protected], see here

Table of Contents

Demo

Demo

Requirements

Installation

npm

$ npm i vue-lazyload -S

yarn

$ yarn add vue-lazyload

CDN

CDN: https://unpkg.com/vue-lazyload/vue-lazyload.js

<script src="https://unpkg.com/vue-lazyload/vue-lazyload.js"></script>
<script>
  Vue.use(VueLazyload)
  ...
</script>

Usage

main.js:

import Vue from 'vue'
import App from './App.vue'
import VueLazyload from 'vue-lazyload'

Vue.use(VueLazyload)

// or with options
const loadimage = require('./assets/loading.gif')
const errorimage = require('./assets/error.gif')

Vue.use(VueLazyload, {
  preLoad: 1.3,
  error: errorimage,
  loading: loadimage,
  attempt: 1
})

new Vue({
  el: 'body',
  components: {
    App
  }
})

template:

<ul>
  <li v-for="img in list">
    <img v-lazy="img.src" >
  </li>
</ul>

use v-lazy-container work with raw HTML

<div v-lazy-container="{ selector: 'img' }">
  <img data-src="//domain.com/img1.jpg">
  <img data-src="//domain.com/img2.jpg">
  <img data-src="//domain.com/img3.jpg">  
</div>

custom error and loading placeholder image

<div v-lazy-container="{ selector: 'img', error: 'xxx.jpg', loading: 'xxx.jpg' }">
  <img data-src="//domain.com/img1.jpg">
  <img data-src="//domain.com/img2.jpg">
  <img data-src="//domain.com/img3.jpg">  
</div>
<div v-lazy-container="{ selector: 'img' }">
  <img data-src="//domain.com/img1.jpg" data-error="xxx.jpg">
  <img data-src="//domain.com/img2.jpg" data-loading="xxx.jpg">
  <img data-src="//domain.com/img3.jpg">  
</div>

Constructor Options

key description default options
preLoad proportion of pre-loading height 1.3 Number
error src of the image upon load fail 'data-src' String
loading src of the image while loading 'data-src' String
attempt attempts count 3 Number
listenEvents events that you want vue listen for ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend', 'touchmove'] Desired Listen Events
adapter dynamically modify the attribute of element { } Element Adapter
filter the image's listener filter { } Image listener filter
lazyComponent lazyload component false Lazy Component
dispatchEvent trigger the dom event false Boolean
throttleWait throttle wait 200 Number
observer use IntersectionObserver false Boolean
observerOptions IntersectionObserver options { rootMargin: '0px', threshold: 0.1 } IntersectionObserver
silent do not print debug info true Boolean

Desired Listen Events

You can configure which events you want vue-lazyload by passing in an array of listener names.

Vue.use(VueLazyload, {
  preLoad: 1.3,
  error: 'dist/error.png',
  loading: 'dist/loading.gif',
  attempt: 1,
  // the default is ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend']
  listenEvents: [ 'scroll' ]
})

This is useful if you are having trouble with this plugin resetting itself to loading when you have certain animations and transitions taking place

Image listener filter

dynamically modify the src of image

Vue.use(vueLazy, {
    filter: {
      progressive (listener, options) {
          const isCDN = /qiniudn.com/
          if (isCDN.test(listener.src)) {
              listener.el.setAttribute('lazy-progressive', 'true')
              listener.loading = listener.src + '?imageView2/1/w/10/h/10'
          }
      },
      webp (listener, options) {
          if (!options.supportWebp) return
          const isCDN = /qiniudn.com/
          if (isCDN.test(listener.src)) {
              listener.src += '?imageView2/2/format/webp'
          }
      }
    }
})

Element Adapter

Vue.use(vueLazy, {
    adapter: {
        loaded ({ bindType, el, naturalHeight, naturalWidth, $parent, src, loading, error, Init }) {
            // do something here
            // example for call LoadedHandler
            LoadedHandler(el)
        },
        loading (listender, Init) {
            console.log('loading')
        },
        error (listender, Init) {
            console.log('error')
        }
    }
})

IntersectionObserver

use Intersection Observer to to improve performance of a large number of nodes.

Vue.use(vueLazy, {
  // set observer to true
  observer: true,

  // optional
  observerOptions: {
    rootMargin: '0px',
    threshold: 0.1
  }
})

Lazy Component

Vue.use(VueLazyload, {
  lazyComponent: true
});
<lazy-component @show="handler">
  <img class="mini-cover" :src="img.src" width="100%" height="400">
</lazy-component>

<script>
  {
    ...
    methods: {
      handler (component) {
        console.log('this component is showing')
      }
    }

  }
</script>

Use in list

<lazy-component v-for="(item, index) in list" :key="item.src" >
  <img class="mini-cover" :src="item.src" width="100%" height="400">
</lazy-component>

Implementation

Basic

vue-lazyload will set this img element's src with imgUrl string

<script>
export default {
  data () {
    return {
      imgObj: {
        src: 'http://xx.com/logo.png',
        error: 'http://xx.com/error.png',
        loading: 'http://xx.com/loading-spin.svg'
      },
      imgUrl: 'http://xx.com/logo.png' // String
    }
  }
}
</script>

<template>
  <div ref="container">
     <img v-lazy="imgUrl"/>
     <div v-lazy:background-image="imgUrl"></div>

     <!-- with customer error and loading -->
     <img v-lazy="imgObj"/>
     <div v-lazy:background-image="imgObj"></div>

     <!-- Customer scrollable element -->
     <img v-lazy.container ="imgUrl"/>
     <div v-lazy:background-image.container="img"></div>

    <!-- srcset -->
    <img v-lazy="'img.400px.jpg'" data-srcset="img.400px.jpg 400w, img.800px.jpg 800w, img.1200px.jpg 1200w">
    <img v-lazy="imgUrl" :data-srcset="imgUrl' + '?size=400 400w, ' + imgUrl + ' ?size=800 800w, ' + imgUrl +'/1200.jpg 1200w'" />
  </div>
</template>

CSS state

There are three states while img loading

loading loaded error

<img src="imgUrl" lazy="loading">
<img src="imgUrl" lazy="loaded">
<img src="imgUrl" lazy="error">
<style>
  img[lazy=loading] {
    /*your style here*/
  }
  img[lazy=error] {
    /*your style here*/
  }
  img[lazy=loaded] {
    /*your style here*/
  }
  /*
  or background-image
  */
  .yourclass[lazy=loading] {
    /*your style here*/
  }
  .yourclass[lazy=error] {
    /*your style here*/
  }
  .yourclass[lazy=loaded] {
    /*your style here*/
  }
</style>

Methods

Event Hook

vm.$Lazyload.$on(event, callback) vm.$Lazyload.$off(event, callback) vm.$Lazyload.$once(event, callback)

  • $on Listen for a custom events loading, loaded, error
  • $once Listen for a custom event, but only once. The listener will be removed once it triggers for the first time.
  • $off Remove event listener(s).

vm.$Lazyload.$on

Arguments:

  • {string} event
  • {Function} callback

Example

vm.$Lazyload.$on('loaded', function ({ bindType, el, naturalHeight, naturalWidth, $parent, src, loading, error }, formCache) {
  console.log(el, src)
})

vm.$Lazyload.$once

Arguments:

  • {string} event
  • {Function} callback

Example

vm.$Lazyload.$once('loaded', function ({ el, src }) {
  console.log(el, src)
})

vm.$Lazyload.$off

If only the event is provided, remove all listeners for that event

Arguments:

  • {string} event
  • {Function} callback

Example

function handler ({ el, src }, formCache) {
  console.log(el, src)
}
vm.$Lazyload.$on('loaded', handler)
vm.$Lazyload.$off('loaded', handler)
vm.$Lazyload.$off('loaded')

LazyLoadHandler

vm.$Lazyload.lazyLoadHandler

Manually trigger lazy loading position calculation

Example

this.$Lazyload.lazyLoadHandler()

Performance

this.$Lazyload.$on('loaded', function (listener) {
  console.table(this.$Lazyload.performance())
})

performance-demo

Dynamic switching pictures

 <img v-lazy="lazyImg" :key="lazyImg.src">

Authors && Contributors

License

The MIT License

More Repositories

1

vue-progressbar

A lightweight progress bar for vue
JavaScript
1,458
star
2

vue-recyclerview

Mastering Large Lists with the vue-recyclerview
JavaScript
1,451
star
3

vue-zhihu-daily

zhihu daily spa with vue 线上演示在这里 ---->
JavaScript
1,287
star
4

vue-dragging

A sortable list directive with Vue
JavaScript
765
star
5

vue-datepicker

[Deprecated] calendar and datepicker component with material design for Vue.js
Vue
703
star
6

vue-video

A HTML5 video player component for Vue.js
Vue
328
star
7

vue-ssr-hmr-template

Interesting! Vue2 + Webpack2 + HMR + Server Side Render + Express template see demo->
JavaScript
226
star
8

vue-mobile-qq

一个长得像QQ的demo
Vue
221
star
9

vue-vueRouter-webpack-example

a vue webpack example
CSS
212
star
10

vue-slide

A lightweight slide component for vue
JavaScript
208
star
11

weapp-gold

微信小程序的掘金信息流
JavaScript
169
star
12

Qarticles

A lightweight and high performance JavaScript library for creating physical particles
JavaScript
136
star
13

vue-ssr

Use Vue 2.0 Server Side Rendering with Express
JavaScript
93
star
14

zhihu-beautify

beautify your zhihu
CSS
85
star
15

vue-material-blog

a simple blog make by Vue and Material-design-lite
Vue
65
star
16

safari-reaper-demo

HTML
33
star
17

weex-demo

掘金weex版demo
JavaScript
26
star
18

AweSiteChat

A horrible site danmu project base on Vue.js & Wilddog
Vue
21
star
19

vue-audio

A audio player for vue.js
Vue
16
star
20

cov-xss

xss
Vue
9
star
21

cov_localStorageORM

javascript ORM base on Localstorage
JavaScript
8
star
22

CovBookkeeper

vue+echart+express实现的记账web app
JavaScript
4
star
23

weapp-shop

O2O 电商微信小程序
JavaScript
4
star
24

vue-recyclerview-example

vue-recyclerview example
JavaScript
3
star
25

gold-card

nothing here
JavaScript
3
star
26

hatest

A node API testing tool similar to Supertest, based on Axios.
JavaScript
2
star
27

sync-console

realtime remote sync console
JavaScript
2
star
28

koa-server-arm

JavaScript
2
star
29

want-to-eat

使用vue.js做的一个简单material design风格小web app
JavaScript
2
star
30

sync-console-server

real time remote debug tool server side
JavaScript
2
star
31

vue-lazyload-run

vue-lazyload dev
JavaScript
2
star
32

wazi

amaziUI+ajax+PHP online shop
CSS
1
star
33

v8-RuntimeFunctions-list

V8 RuntimeFunctions list
1
star
34

css-rewrite-webpack-plugin

A Webpack plugin to rewrite CSS assets.
JavaScript
1
star
35

cov-rate-limit

A lightweight Rate limiter middleware for Express and Koa. Use to limit repeated requests to public APIs.
JavaScript
1
star
36

xss-demo

xss-demo
Vue
1
star
37

vue-ssr-demo

1
star