defer image loading

This commit is contained in:
2018-12-29 11:23:40 -08:00
parent c6eb48ca87
commit 7487364571
4 changed files with 101 additions and 16 deletions

View File

@@ -6,19 +6,43 @@ export interface Props {
image: Model.Image;
onClick: () => void;
width: number;
defer?: boolean;
}
export interface State {
hasLoadedOnce: boolean;
}
interface SrcSetInfo {
srcSet: string;
bestSrc: string;
srcSet: string;
bestSrc: string;
}
export class Picture extends React.PureComponent<Props, {}> {
export class Picture extends React.PureComponent<Props, State> {
static displayName = "Picture";
state: State = {
hasLoadedOnce: false
};
static getDerivedStateFromProps(props: Props, state: State): State | null {
return !state.hasLoadedOnce && !props.defer
? { hasLoadedOnce: true }
: null;
}
render() {
if (this.props.defer && !this.state.hasLoadedOnce) {
return (
<div
className="Picture-defer"
style={{ width: this.props.width + "px" }}
/>
);
}
const srcSet = this._srcset();
return (
<img
onClick={this.props.onClick}
@@ -44,18 +68,18 @@ export class Picture extends React.PureComponent<Props, {}> {
if (scale >= 1) {
srcs.push(`img/${size}/${this.props.image.src} ${scale}x`);
if (scale < bestRatio) {
bestSize = size;
bestRatio = scale;
}
if (scale < bestRatio) {
bestSize = size;
bestRatio = scale;
}
}
});
srcs.push(`img/${bestSize}/${this.props.image.src} 1x`);
srcs.push(`img/${bestSize}/${this.props.image.src} 1x`);
return {
srcSet: srcs.join(","),
bestSrc: `img/${bestSize}/${this.props.image.src}`
srcSet: srcs.join(","),
bestSrc: `img/${bestSize}/${this.props.image.src}`
};
};
}