Skip to content

Instantly share code, notes, and snippets.

@jongacnik
Created December 30, 2020 05:49
Show Gist options
  • Select an option

  • Save jongacnik/d4183098e1ae59caac1b51ed80abd015 to your computer and use it in GitHub Desktop.

Select an option

Save jongacnik/d4183098e1ae59caac1b51ed80abd015 to your computer and use it in GitHub Desktop.

Revisions

  1. jongacnik created this gist Dec 30, 2020.
    40 changes: 40 additions & 0 deletions Ultralazy.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    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')
    }
    })