Skip to content

Instantly share code, notes, and snippets.

@rriixx
Last active October 6, 2020 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rriixx/cc0ec9635bc3cc54204fc6e63a72c64c to your computer and use it in GitHub Desktop.
Save rriixx/cc0ec9635bc3cc54204fc6e63a72c64c to your computer and use it in GitHub Desktop.
Native Lazy Loading
export default class LazyLoadingFeature {
supported = false
detect () {
if (typeof HTMLImageElement === 'undefined') return
this.supported = HTMLImageElement && 'loading' in HTMLImageElement.prototype
}
polyfill () {
if (this.supported) return
// Dynamically import the lazysizes library
import(/* webpackChunkName: "lazysizes" */ 'lazysizes')
.catch(err => console.log('failed to load lazysizes module', err))
}
}
import LazyLoadingFeature from 'src/helpers/lazy-loading-feature'
import { DirectiveBinding } from 'vue/types/options'
const lazyLoadingFeature = new LazyLoadingFeature()
lazyLoadingFeature.detect()
lazyLoadingFeature.polyfill()
const directive = {
prepareElem (el: HTMLImageElement, binding: DirectiveBinding) { // no hook func
// set src attribute for the bound `img` element
if (lazyLoadingFeature.supported && el.dataset.src) {
el.src = el.dataset.src
el.classList.add('lazyloaded')
el.classList.remove('lazyload')
if (!binding.value?.error) return
// set pixel on error / failed to load image
el.onerror = () => {
el.src = binding.value.error
}
}
},
bind (el: HTMLImageElement, binding: DirectiveBinding) {
// support lazy loading for background image
if (binding.arg === 'background-image' && binding.value) el.style.backgroundImage = `url("${binding.value}")`
directive.prepareElem(el, binding)
},
update (el: HTMLImageElement, binding: DirectiveBinding) {
directive.prepareElem(el, binding)
}
}
export default directive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment