Skip to content

Instantly share code, notes, and snippets.

@jongacnik
Created December 30, 2020 05:49
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 jongacnik/d4183098e1ae59caac1b51ed80abd015 to your computer and use it in GitHub Desktop.
Save jongacnik/d4183098e1ae59caac1b51ed80abd015 to your computer and use it in GitHub Desktop.
Ultralazy: Lazy load wicked component
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