Last active
September 3, 2019 00:55
-
-
Save kilgarenone/c733026630874cd68e06197071b2534e to your computer and use it in GitHub Desktop.
lazy loading image
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
import { h, Component } from "preact"; | |
class LazyLoadingImage extends Component { | |
state = { lazyLoaded: false, source: "" }; | |
componentDidUpdate() { | |
// the key here is the `inVisible` prop of which value is passed from the `Observer` component! | |
if (!this.state.lazyLoaded && this.props.isVisible) { | |
this.getBgImage(); | |
} | |
} | |
getBgImage = async () => { | |
// that webpackMode: "eager" is crucial to prevent webpack from generating useless .js file for each of your images! | |
const { default: source } = await import(/* webpackMode: "eager" */ `./images/${this.props.imgName}.png`); | |
this.setState(prevState => ({ source, lazyLoaded: true })); | |
}; | |
render({}, { source }) { | |
// data-src attr prevents <img> from doing anything | |
const src = source ? { src: source } : { "data-src": '' }; | |
return ( | |
<div> | |
<img {...src} /> | |
</div> | |
); | |
} | |
} | |
export default LazyLoadingImage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment