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

如何解决Cloudfront第三方代码阻塞问题,提升Lighthouse评分?

修复第三方代码阻塞主线程问题,提升Lighthouse评分

针对你的Gatsby网站遇到的第三方代码阻塞主线程问题(Cloudfront JS占962ms、Google Analytics占39ms),可以按以下方案逐一优化:

一、优化Google Analytics加载

1. 切换到GA4兼容插件并配置延迟加载

旧的gatsby-plugin-google-analytics基于传统analytics.js,建议替换为支持GA4的gatsby-plugin-google-gtag,通过配置减少主线程阻塞:

  • 卸载旧插件:
    npm uninstall gatsby-plugin-google-analytics
    
  • 安装新插件:
    npm install gatsby-plugin-google-gtag
    
  • 在gatsby-config.js中配置:
    module.exports = {
      plugins: [
        {
          resolve: `gatsby-plugin-google-gtag`,
          options: {
            trackingIds: ["你的GA跟踪ID"],
            gtagConfig: {
              anonymize_ip: true,
            },
            pluginConfig: {
              head: false, // 将脚本放在body底部,避免阻塞首屏渲染
              respectDNT: true,
              delayOnRouteUpdate: 1000, // 延迟1秒发送页面视图,等待主线程空闲
            },
          },
        },
      ],
    }
    

2. 手动控制加载时机(可选)

如果需要更精细的控制,可在页面完全加载后再注入GA脚本:

import { useEffect } from 'react'

const useGoogleAnalytics = () => {
  useEffect(() => {
    const loadGA = () => {
      window.dataLayer = window.dataLayer || []
      function gtag(){dataLayer.push(arguments)}
      gtag('js', new Date())
      gtag('config', '你的GA跟踪ID')
    }

    if (document.readyState === 'complete') {
      loadGA()
    } else {
      window.addEventListener('load', loadGA)
      return () => window.removeEventListener('load', loadGA)
    }
  }, [])
}

export default useGoogleAnalytics

二、解决Cloudfront JS阻塞问题(核心优化点)

从依赖列表判断,阻塞的Cloudfront JS大概率是@pittica/gatsby-plugin-recaptcha加载的reCAPTCHA脚本,可通过以下方式优化:

1. 异步加载reCAPTCHA组件

使用@loadable/component仅在需要reCAPTCHA的场景(如联系表单)才加载对应组件,避免首屏加载阻塞:

import loadable from '@loadable/component'

// 异步加载包含reCAPTCHA的表单组件
const ContactForm = loadable(() => import('./components/ContactForm'), {
  fallback: <div>加载表单中...</div>,
})

const ContactPage = () => {
  return (
    <div>
      <h1>联系我们</h1>
      <ContactForm />
    </div>
  )
}

export default ContactPage

2. 替换为reCAPTCHA v3

reCAPTCHA v3是隐形验证机制,无需加载弹窗UI脚本,阻塞时间远低于v2:

  • 移除旧插件:
    npm uninstall @pittica/gatsby-plugin-recaptcha
    
  • 手动实现v3验证逻辑:
    import { useEffect, useState } from 'react'
    
    const ContactForm = () => {
      const [token, setToken] = useState('')
    
      useEffect(() => {
        const script = document.createElement('script')
        script.src = `https://www.google.com/recaptcha/api.js?render=你的reCAPTCHA v3密钥`
        script.async = true
        script.defer = true
        document.body.appendChild(script)
    
        script.onload = () => {
          window.grecaptcha.ready(() => {
            window.grecaptcha.execute('你的reCAPTCHA v3密钥', { action: 'submit' })
              .then(setToken)
          })
        }
    
        return () => document.body.removeChild(script)
      }, [])
    
      const handleSubmit = (e) => {
        e.preventDefault()
        // 提交逻辑,携带token完成验证
      }
    
      return (
        <form onSubmit={handleSubmit}>
          {/* 表单内容 */}
          <input type="hidden" name="g-recaptcha-response" value={token} />
          <button type="submit">提交</button>
        </form>
      )
    }
    
    export default ContactForm
    

3. 预连接资源域名

通过gatsby-plugin-preconnect预连接reCAPTCHA的资源域名,减少DNS解析和TCP握手时间:
在gatsby-config.js中添加:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-preconnect`,
      options: {
        domains: ['https://www.google.com', 'https://www.gstatic.com'],
      },
    },
  ],
}

三、通用Gatsby性能优化

  1. 开启Netlify资源优化:在Netlify后台「Site settings > Build & deploy > Post processing > Asset optimization」中,开启「Delay loading third-party scripts」,Netlify会自动延迟第三方脚本加载直到用户交互。
  2. 清理冗余依赖:移除项目中未使用的依赖(如jshint),减少打包体积和加载压力。
  3. 强化代码分割:确保所有非首屏必需的组件都通过@loadable/component异步加载,进一步拆分代码块。

内容的提问来源于stack exchange,提问作者Sam Germain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 22:48:09