Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Vue module for lazy-loading images in your vue 3 applications.

License

NotificationsYou must be signed in to change notification settings

jambonn/vue-lazyload

Repository files navigation

Vue module for lazyloading images in your Vue 3 applications. This module is base on vue-lazyload. Vue 1.x or 2.x please usevue-lazyload. 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 Vue 3

Table of Contents

Requirements

Installation

npm

$ npm i @jambonn/vue-lazyload

yarn

$ yarn add @jambonn/vue-lazyload

CDN

CDN:https://unpkg.com/@jambonn/vue-lazyload/dist/vue-lazyload.umd.js

<scriptsrc="https://unpkg.com/@jambonn/vue-lazyload/dist/vue-lazyload.umd.js"></script><script>varAttributeBindingApp={data(){return{message:'Vue Lazyload'}}}varapp=Vue.createApp(AttributeBindingApp)app.use(window['vue-lazyload'].default)app.mount('#bind-attribute')...</script>

Usage

main.js:

import{createApp}from'vue'importVueLazyloadfrom'@jambonn/vue-lazyload'importAppfrom'./App.vue'constapp=createApp(App)app.use(VueLazyload)// or with optionsconstloadimage=require('./assets/loading.gif')consterrorimage=require('./assets/error.gif')app.use(VueLazyload,{preLoad:1.3,error:errorimage,loading:loadimage,attempt:1})app.mount('#app')

template:

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

usev-lazy-container work with raw HTML

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

customerror andloading placeholder image

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

Constructor Options

keydescriptiondefaultoptions
preLoadproportion of pre-loading height1.3Number
errorsrc of the image upon load fail'data-src'String
loadingsrc of the image while loading'data-src'String
attemptattempts count3Number
listenEventsevents that you want vue listen for['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend', 'touchmove']Desired Listen Events
adapterdynamically modify the attribute of element{ }Element Adapter
filterthe image's listener filter{ }Image listener filter
lazyComponentlazyload componentfalseLazy Component
dispatchEventtrigger the dom eventfalseBoolean
throttleWaitthrottle wait200Number
observeruse IntersectionObserverfalseBoolean
observerOptionsIntersectionObserver options{ rootMargin: '0px', threshold: 0.1 }IntersectionObserver
silentdo not print debug infotrueBoolean

Desired Listen Events

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

constapp=createApp(AttributeBindingApp)app.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 loadingwhen you have certain animations and transitions taking place

Image listener filter

dynamically modify the src of image

constapp=createApp(AttributeBindingApp)app.use(VueLazyload,{filter:{progressive(listener,options){constisCDN=/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)returnconstisCDN=/qiniudn.com/if(isCDN.test(listener.src)){listener.src+='?imageView2/2/format/webp'}}}})

Element Adapter

constapp=createApp(AttributeBindingApp)app.use(VueLazyload,{adapter:{loaded({ bindType, el, naturalHeight, naturalWidth, $parent, src, loading, error, Init}){// do something here// example for call LoadedHandlerLoadedHandler(el)},loading(listender,Init){console.log('loading')},error(listender,Init){console.log('error')}}})

IntersectionObserver

useIntersection Observer to to improve performance of a large number of nodes.

constapp=createApp(AttributeBindingApp)app.use(vueLazy,{// set observer to trueobserver:true,// optionalobserverOptions:{rootMargin:'0px',threshold:0.1}})

Lazy Component

constapp=createApp(AttributeBindingApp)app.use(VueLazyload,{lazyComponent:true});
<lazy-component@show="handler"><imgclass="mini-cover":src="img.src"width="100%"height="400"></lazy-component><script>exportdefault{setup(){consthandler=()=>{console.log('this component is showing')}return{ handler}}}</script>

Use in list

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

Implementation

Basic

vue-lazyload will set this img element'ssrc withimgUrl string

<template><div"><imgv-lazy="imgUrl"/><divv-lazy:background-image="imgUrl"></div><!-- with customer error and loading --><imgv-lazy="imgObj"/><divv-lazy:background-image="imgObj"></div><!-- Customer scrollable element --><imgv-lazy.container ="imgUrl"/><divv-lazy:background-image.container="img"></div><!-- srcset --><imgv-lazy="'img.400px.jpg'"data-srcset="img.400px.jpg 400w, img.800px.jpg 800w, img.1200px.jpg 1200w"><imgv-lazy="imgUrl":data-srcset="imgUrl' + '?size=400 400w, ' + imgUrl + ' ?size=800 800w, ' + imgUrl +'/1200.jpg 1200w'"/></div></template><script>import{ref,reactive}from'vue'exportdefault{setup(){constimgObj=reactive({src:'http://xx.com/logo.png',error:'http://xx.com/error.png',loading:'http://xx.com/loading-spin.svg'})constimgUrl=ref('http://xx.com/logo.png')// Stringreturn{ imgObj, imgUrl}}}</script>

CSS state

There are three states while img loading

loadingloadederror

<imgsrc="imgUrl"lazy="loading"><imgsrc="imgUrl"lazy="loaded"><imgsrc="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

import{getCurrentInstance,inject}from'vue'exportdefault{setup(){constinternalInstance=getCurrentInstance().appContext.config.globalPropertiesconstLazyLoad=internalInstance.$Lazyload// orconstLazyload=inject('Lazyload')Lazyload.$on(event,callback)Lazyload.$off(event,callback)Lazyload.$once(event,callback)}}
  • $on Listen for a custom eventsloading,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).

Lazyload.$on

Arguments:

  • {string} event
  • {Function} callback

Example

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

Lazyload.$once

Arguments:

  • {string} event
  • {Function} callback

Example

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

Lazyload.$off

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

Arguments:

  • {string} event
  • {Function} callback

Example

import{getCurrentInstance,inject}from'vue'exportdefault{setup(){constinternalInstance=getCurrentInstance().appContext.config.globalPropertiesconstLazyLoad=internalInstance.$Lazyload// orconstLazyload=inject('Lazyload')consthandler=({ el, src},formCache)=>{console.log(el,src)}Lazyload.$on('loaded',handler)Lazyload.$off('loaded',handler)Lazyload.$off('loaded')}}

LazyLoadHandler

Lazyload.lazyLoadHandler

Manually trigger lazy loading position calculation

Example

import{getCurrentInstance,inject}from'vue'exportdefault{setup(){constinternalInstance=getCurrentInstance().appContext.config.globalPropertiesconstLazyLoad=internalInstance.$Lazyload// orconstLazyload=inject('Lazyload')Lazyload.lazyLoadHandler()}}

Performance

import{getCurrentInstance,inject}from'vue'exportdefault{setup(){constinternalInstance=getCurrentInstance().appContext.config.globalPropertiesconstLazyLoad=internalInstance.$Lazyload// orconstLazyload=inject('Lazyload')Lazyload.$on('loaded',function(listener){console.table(Lazyload.performance())})}}

performance-demo

Dynamic switching pictures

 <imgv-lazy="lazyImg" :key="lazyImg.src">

Authors && Contributors

License

The MIT License

About

Vue module for lazy-loading images in your vue 3 applications.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors2

  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp