I'm working on a Gatsby project that has a large (about 300kb) SVG component. Is there a way to lazy load this component, ideally displaying a loading spinner? I would like to prevent the large SVG from negatively impacting the first paint. Some elements of this component have event listeners and click events to route the user to different pages, so it's not just a static SVG image.
import React from "react";
import { navigate } from "gatsby";
const clickEventHandler = () => {
// some logic
// ...
navigate("/path")
};
export default function SVGMap() {
//... some component logic ...
return (
<svg id='very-large-svg'>
<path d="" style={{...}} onClick={clickEventHandler} />
</svg>
)};
In my landing page I would like to use this element
import SVGMap from './svgmap.js'
export default function Page() {
return(
<>
{/* Lazy load this while the rest of the page is already being displayed */}
<SVGMap />
</>
)
};
Is there any way how to do this?
You can use React.lazy with suspense for code-splitting.
const SVGMap = React.lazy(() => import('./svgmap'));
<Suspense fallback={""}>
<SVGMap />
</Suspense>
https://tr.reactjs.org/docs/code-splitting.html#reactlazy
or you can use @loadable/component 3th party libary.
import loadable from '@loadable/component'
const SVGMap = loadable(() => import('./svgmap'))