Skip to content

Instantly share code, notes, and snippets.

@innermond
Created January 26, 2020 21:29
Show Gist options
  • Save innermond/532c4debf38443b6e4b39400bb2aabda to your computer and use it in GitHub Desktop.
Save innermond/532c4debf38443b6e4b39400bb2aabda to your computer and use it in GitHub Desktop.
intersection observer
<style>
#box {
background-color: rgba(40, 40, 190, 255);
border: 4px solid rgb(20, 20, 120);
transition: background-color 1s, border 1s;
width: 100%;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: center;
align-content: flex-start;
}
img.late {
max-width: 100%;
height: 150px;
max-height: 150px;
flex: 0 1 auto;
}
</style>
<script>
window.addEventListener('DOMContentLoaded', evt => {
let url, img
let box = document.querySelector('#box')
for (let inf of waterfall) {
url = inf[0]
img = new Image()
img.classList.add('late')
img.dataset.src = url
img.dataset.placeholder = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
img.width = inf[1]
img.height = inf[2]
let r = inf[1]/inf[2]
box.appendChild(img)
let hx = parseFloat(window.getComputedStyle(img).height)
let wx = r*hx
img.style.width = wx + 'px'
}
let options = {
root: null,
rootMargin:'-250px 0px',
//rootMargin:'0px',
threshold: 0.0
}
let callback = xx => {
xx.forEach(x => {
if (x.isIntersecting) {
window.requestAnimationFrame(()=>x.target.src = x.target.dataset.src)
} else {
window.requestAnimationFrame(()=>x.target.src = x.target.dataset.placeholder)
}
})
}
let observer = new IntersectionObserver(callback, options)
document.querySelectorAll('img[class~=late]').forEach(target => observer.observe(target));
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment