Last active
October 6, 2020 07:42
-
-
Save rriixx/cc0ec9635bc3cc54204fc6e63a72c64c to your computer and use it in GitHub Desktop.
Native Lazy Loading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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