Created
April 27, 2019 06:58
-
-
Save shqld/f9161679f181932e2ba6e058c6767282 to your computer and use it in GitHub Desktop.
A toy LazyLoader built with WebComponents/CustomElement
This file contains hidden or 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
<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