Skip to content

Instantly share code, notes, and snippets.

@kilgarenone
Last active September 3, 2019 00:55
Show Gist options
  • Save kilgarenone/c733026630874cd68e06197071b2534e to your computer and use it in GitHub Desktop.
Save kilgarenone/c733026630874cd68e06197071b2534e to your computer and use it in GitHub Desktop.
lazy loading image
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