You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新建React应用Lighthouse性能评分偏低的原因及优化方案咨询

Why Your New React App Has a 28 Lighthouse Performance Score & How to Fix It

Trust me, I’ve seen plenty of new React apps start with scores this low—most of the time it’s just a handful of easy-to-fix issues dragging down performance. Let’s break down the common culprits first, then jump into concrete steps to boost that score.

Common Reasons for That Low Score

  • Bloated, Unoptimized Bundle: If you’re using Create React App (or a similar starter), your production build might be shipping the full React library, unused dependencies, and unminified code all in one big file. Lighthouse will flag this as "Reduce unused JavaScript" and "Minify assets".
  • Client-Side Rendering (CSR) Lag: Pure CSR means the browser has to download your entire bundle, parse it, and then render the page—this leads to slow First Contentful Paint (FCP) and Largest Contentful Paint (LCP), which are huge parts of the performance score.
  • Unoptimized Images: Large, uncompressed JPEGs/PNGs, or images sized way bigger than their display container, are a classic performance killer. Lighthouse will call out "Properly size images" and "Serve next-gen formats".
  • Missing Compression: Your server isn’t using gzip or Brotli to shrink static assets, so downloads take way longer than they need to.
  • No Caching Rules: Static files (JS, CSS, images) don’t have long-term cache headers, so users re-download everything on every visit.
  • Unnecessary Third-Party Scripts: Even small analytics or social widgets add load time and block rendering if not handled right.

Actionable Fixes to Boost Your Score

Let’s go step-by-step through changes that will make an immediate impact:

1. Trim Your Bundle Size

  • Use Production Builds: First off, always test Lighthouse against your production build (run npm run build for CRA)—the development build is intentionally unoptimized. CRA automatically minifies code and removes unused exports in production, but custom setups need tree shaking enabled in Webpack/Rollup.
  • Split Your Code: Use React’s React.lazy() and Suspense to split your app into smaller chunks that load only when needed. For example:
    const Dashboard = React.lazy(() => import('./pages/Dashboard'));
    
    function App() {
      return (
        <Suspense fallback={<div>Loading...</div>}>
          <Routes>
            <Route path="/dashboard" element={<Dashboard />} />
          </Routes>
        </Suspense>
      );
    }
    
  • Cut Unused Dependencies: Run npm ls to spot packages you don’t actually use, or use webpack-bundle-analyzer to visualize your bundle and find bloat. For example, if you’re importing an entire UI library like Material UI but only using 2 components, switch to importing just those components instead.

2. Fix Slow Rendering (FCP/LCP)

  • Pre-Render Pages: Switch to SSR or SSG with tools like Next.js or Gatsby—this pre-renders your pages on the server or at build time, so the browser gets fully rendered HTML immediately. If you want to stick with CRA, try react-snap to pre-render static pages.
  • Inline Critical CSS: Extract the CSS needed for the first screen and inline it in your <head>—this prevents render-blocking CSS. For CRA, you can use react-app-rewire-critical-css to set this up.
  • Defer Non-Critical JS: Use defer/async on non-essential scripts, or load them dynamically after the page renders. For example, load analytics scripts only after the user interacts with the page.

3. Optimize Images (Big Win!)

  • Compress & Resize: Use tools like Squoosh or Sharp to shrink image sizes. Make sure images are exactly the size they’re displayed at—don’t load a 2000px-wide image for a 300px container.
  • Serve Next-Gen Formats: Convert images to WebP or AVIF—they’re 25-50% smaller than JPEG/PNG with the same quality. Use next/image (if on Next.js) or react-image-webp to serve these with fallbacks for older browsers.
  • Lazy Load Offscreen Images: Add loading="lazy" to images that aren’t in the initial viewport, or use React’s IntersectionObserver for more control over when images load.

4. Enable Compression & Caching

  • Turn On Gzip/Brotli: Configure your server (Nginx, Apache, or your hosting provider) to compress static assets. For Nginx, add this to your config:
    gzip on;
    gzip_types text/plain text/css application/javascript application/json;
    brotli on;
    brotli_types text/plain text/css application/javascript application/json;
    
  • Set Cache Headers: For assets with hashed filenames (CRA generates these in production), set Cache-Control: public, max-age=31536000, immutable so browsers cache them for a year. For non-hashed files, use a shorter cache time (like 7 days).

5. Clean Up Third-Party Scripts

  • Remove What You Don’t Need: If you added analytics or social widgets that aren’t critical right now, remove them temporarily to see if your score jumps. You can add them back later with better loading strategies.
  • Load Scripts Asynchronously: Wrap third-party scripts in dynamic imports or use async to prevent them from blocking rendering. Example:
    useEffect(() => {
      const loadScript = async () => {
        const script = document.createElement('script');
        script.src = 'https://example.com/analytics.js';
        script.async = true;
        document.body.appendChild(script);
      };
      // Wait until the page is interactive to load
      if (document.readyState === 'interactive') loadScript();
      else window.addEventListener('DOMContentLoaded', loadScript);
    }, []);
    

6. Iterate with Lighthouse

After making these changes, build your app again, serve the production version, and run Lighthouse once more. Focus on the top issues it flags—Lighthouse gives specific, actionable tips for each problem, so use those to guide your next tweaks.

内容的提问来源于stack exchange,提问作者Accounting4me Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:57:37