Created
December 30, 2020 05:49
-
-
Save jongacnik/d4183098e1ae59caac1b51ed80abd015 to your computer and use it in GitHub Desktop.
Ultralazy: Lazy load wicked component
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 { define } from 'wicked-elements' | |
import onIntersect from '../lib/on-intersect.js' | |
define('[data-component~="ultralazy"]', { | |
init () { | |
this.state = {} | |
this.onEnter = this.onEnter.bind(this) | |
this.onLoad = this.onLoad.bind(this) | |
}, | |
connected () { | |
this.stopObserving = onIntersect(this.element, this.onEnter) | |
this.element.addEventListener('load', this.onLoad) | |
}, | |
disconnected () { | |
this.stopObserving() | |
}, | |
onEnter (e) { | |
this.load() | |
this.stopObserving() | |
}, | |
load () { | |
this.element.classList.remove('lazyload') | |
this.element.classList.add('lazyloading') | |
const newSrc = this.element.dataset.src | |
if (newSrc) this.element.src = newSrc | |
const newSrcset = this.element.dataset.srcset | |
if (newSrcset) { | |
if (this.element.dataset.sizes === 'auto') { | |
this.element.sizes = `${this.element.offsetWidth}px` | |
} | |
this.element.srcset = newSrcset | |
} | |
}, | |
onLoad () { | |
this.element.classList.remove('lazyloading') | |
this.element.classList.add('lazyloaded') | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment