Search code examples
reactjswebpacknext.jspagespeedlighthouse

reduce JS execution time with NextJS


I have a website that I'm trying to optimize lighthouse page speed ranking. I just switched from SSR with nginx caching to next export using exportPathMap and getInitialProps (also with nginx caching).

Specific page of interest gets heavy traffic

After switching to static, the first content image appears loads in 2-2.5s for "slow 3G". However JS execution time takes like 3-6 seconds.

enter image description here

Questions:

  1. Why does script evaluation take 3-6s when I am using a static export, I was under the impression it would be quite fast?

  2. Are there ways to optimize nextjs JS execution time? Or maybe a webpack setting?


Solution

  • Try wrapping some heavy modules like this:

    import dynamic from 'next/dynamic';
    import { Spinner } from './spinner';
    
    const MyLazyLoadedHeavyComponent = dynamic(() => import('./my-heavy-component'), {
      ssr: false,
      loading: () => <Spinner />
    });
    
    export const MyQuicklyLoadingPage: FC = () => {
      return (
        <div>
          <h1>Welcome to the page!</h1>
          <p>You'll see this text</p>
          <p>Before we load the heavy stuff below</p>
          <p>Large markdown files containing lots of images, etc.</p>
          <MyLazyLoadedHeavyComponent />
        </div>
      );
    };
    

    I also use this sometimes for modules that can't be rendered with SSR.

    Also, evaluate whether something like attempting to use Preact will improve performance. I don't know how easy to do that is with nextJS. I found this https://github.com/developit/nextjs-preact-demo