Skip to content

Instantly share code, notes, and snippets.

@shqld
Created April 27, 2019 06:58
Show Gist options
  • Save shqld/f9161679f181932e2ba6e058c6767282 to your computer and use it in GitHub Desktop.
Save shqld/f9161679f181932e2ba6e058c6767282 to your computer and use it in GitHub Desktop.
A toy LazyLoader built with WebComponents/CustomElement
<style>
.container {
display: flex;
flex-direction: row;
height: 1000px;
}
.item {
flex: 1;
}
</style>
<div class="container">
<div class="item" style="background: cadetblue"></div>
<my-lazyloader class="item" src="/lazy.html" delay="500">
<div style="display: none;">PlaceHolder</div>
</my-lazyloader>
</div>
<my-lazyloader src="/lazy.html">
<div style="display: none;">PlaceHolder</div>
</my-lazyloader>
<script type="module">
class LazyLoader extends HTMLElement {
connectedCallback() {
const observer = new IntersectionObserver(entries => {
if (!entries.every(entry => entry.isIntersecting)) {
return
}
observer.disconnect()
const delay = this.getAttribute('delay')
if (delay) {
setTimeout(this.load.bind(this), delay)
} else {
this.load()
}
})
observer.observe(this)
}
load() {
console.log('start loading...')
fetch(this.getAttribute('src'))
.then(response => response.text())
.then(this.render.bind(this))
}
render(html) {
console.log('start rendering...')
this.innerHTML = html
}
}
customElements.define('my-lazyloader', LazyLoader)
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment