Skip to content

Instantly share code, notes, and snippets.

@estrattonbailey
Last active June 17, 2019 16:29
Show Gist options
  • Save estrattonbailey/c12972dd4ac969bf2effa55097b69bf9 to your computer and use it in GitHub Desktop.
Save estrattonbailey/c12972dd4ac969bf2effa55097b69bf9 to your computer and use it in GitHub Desktop.
Object Fit + Layzr Lazy Load
const objectFit = document.documentElement.style.hasOwnProperty('objectFit')
const images = Layzr({ threshold: 90 })
images.on('src:after', img => {
let parent = img.parentNode
// optional, to style loaded state
parent.setAttribute('data-lazy', 'is-loaded')
if (!objectFit){
let raw = img.getAttribute('srcset') ? img.getAttribute('srcset') : img.getAttribute('src')
let urls = raw.split(/\,/)
let src = urls[urls.length - 1].replace(/\s[0-9]{1,4}[a-z]/g, '')
parent.style.backgroundImage = `url(${src})`
img.style.opacity = 0
}
})
images.update().check().handlers(true)
@estrattonbailey
Copy link
Author

<div class="object-fit-wrap">
  <img 
    data-normal="image.jpg"
    data-srcset="image.jpg, image.jpg 800w, image.jpg 2x"/>
</div>

@estrattonbailey
Copy link
Author

Add a loader:

<div class="object-fit-wrap" data-lazy>
  <div class="__loader"></div>
  <img 
    data-normal="image.jpg"
    data-srcset="image.jpg, image.jpg 800w, image.jpg 2x"/>
</div>
[data-lazy] {
  img {
    opacity: 0;
    transition: opacity $speedSlow $ease;
  }

  &[data-lazy="is-loaded"] {
    img {
      opacity: 1;
    }

    .__loader {
      opacity: 0;
    }
  }

  .__loader {
    // styles
  }
}

@maxrolon
Copy link

maxrolon commented Sep 1, 2016

A slighter more refined way to get the largest image src from either srcset or src

const img = document.getElementById('img')

const sources = 
  ( img.getAttribute('srcset') || img.getAttribute('src') )
  .split(/\s?,\s?/)
  .reduce( (o, val) => {
    let brk = val.split(/\s|w$/)
    o[ brk[1] || 0 ] = brk[0]
    return o
  }, {} )

const getLg = arr => arr[ Math.max( ...Object.keys(arr) ) ]

const largest = getLg( sources )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment