Currently the google static maps https://developers.google.com/maps/documentation/maps-static/overview takes too long to load which causes a high LCP(large content painting).
The solution would be to load a placeholder image and then once the google static maps IMG is finished loading to replace the placeholder with it. What would be a way to implement this?
I did try this but it didn’t replace the placeholder and always returned false.
JavaScript
x
4
1
function imgLoaded(imgElement) {
2
return imgElement.complete && imgElement.naturalHeight !== 0;
3
}
4
Advertisement
Answer
A simple but effective solution is to use the onLoad
event to update a state and toggle the placeholder visibility, like so:
JavaScript
1
29
29
1
import { useState } from "react";
2
3
const LOADING_GIF_URL = `https://i.stack.imgur.com/kOnzy.gif`;
4
const LARGE_IMAGE_URL = `https://upload.wikimedia.org/wikipedia/commons/f/ff/Pizigani_1367_Chart_10MB.jpg`;
5
6
export default function App() {
7
8
const [imageLoaded, setImageLoaded] = useState(false);
9
10
return (
11
<div>
12
{
13
!imageLoaded ?
14
<img alt="Loading" src={LOADING_GIF_URL} style={{ width: `50px` }} />
15
:
16
`Clear your cache and refresh the page to reload the image`
17
}
18
19
<img
20
alt="Large pic"
21
src={LARGE_IMAGE_URL}
22
style={imageLoaded ? {} : { display: `none` }}
23
onLoad={() => setImageLoaded(true)}
24
/>
25
</div>
26
);
27
}
28
29