Skip to content

Lazy Loading

Aniket Prajapati edited this page Oct 15, 2020 · 3 revisions

lazy loading is a technique using which you can lazily load a component after your page has loaded. Components which are not needed upfront or are too big should be lazy-loaded, for example, lazy-load the comment section component on a blog site. This helps your website to become interactive quickly.

Implementation

Let's create a component lazy as lazy.jsx in the src/components dir.

src/components/lazy.jsx

export default function () {
    return (
        <div style={{backgroundColor:"yellow"}}>
            I am a lazy component
        </div>
    )
}

You can lazy-load this component using LazyLoad(()=>import("../components/lazy"))

Let's edit the coms page to include it in a lazy fashion.

src/pages/coms.jsx

import Wrap from "firejsx/Wrap";
import {hot} from "firejsx/Hot";
import Head from "firejsx/Head";
import Loader from "firejsx/Loader";
import Link from "firejsx/Link";
import LazyLoad from "firejsx/LazyLoad"; //import LazyLoad

Wrap(() => {
    const Lazy = LazyLoad(()=>import("../components/lazy")); //LazyLoad

    return (
        <div>
            <Head>
                <title>Index Page</title>
            </Head>
            <Loader effect={React.useEffect} delay={2000}>
                <span style={{color:"blue"}}>Loading text with 2s delay</span>
                {/*use Loader on page root, delay is optional*/}
            </Loader>
            <br/><br/>
            <Link href="/index">Link to Index Page</Link>
            <Lazy/> {/*Use it is a regular component*/}
        </div>
    )
},hot)

You can also make this Lazy component global if you are doing many state updates.

Loading Bar

If you are lazy loading a heavy component then you might want show a loading bar or text before the component renders.

const Lazy = LazyLoad(()=>import("../components/lazy"),undefined,()=>
        <div>
            Loading...
        </div>
    )

SSR lazy components

To server side render a lazy component you have to add the following to the LazyLoad function

const Lazy = LazyLoad(() => import("./components/lazy"), () => require.resolveWeak("./components/lazy"));

The require.resolveWeak function allows for server side rendering.

Clone this wiki locally