Last active
June 17, 2019 16:29
-
-
Save estrattonbailey/c12972dd4ac969bf2effa55097b69bf9 to your computer and use it in GitHub Desktop.
Object Fit + Layzr Lazy Load
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
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) |
Author
estrattonbailey
commented
Aug 30, 2016
<div class="object-fit-wrap">
<img
data-normal="image.jpg"
data-srcset="image.jpg, image.jpg 800w, image.jpg 2x"/>
</div>
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
}
}
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