Gatsby站点用gatsby-plugin-fullstory引发PageSpeed缓存/未使用脚本问题求解
解决Gatsby中FullStory脚本的PageSpeed缓存与未使用脚本问题
针对你遇到的edge.fullstory.com/s/fs.js的缓存和未使用脚本问题,以下是几种无需自托管插件的解决方案:
1. 按需加载脚本(解决未使用脚本问题)
直接卸载gatsby-plugin-fullstory,在需要统计的页面手动加载脚本,避免全局注入导致非目标页面出现未使用脚本警告。
示例代码(在Layout组件中根据路径判断加载):
import { useEffect } from 'react'; import { useLocation } from '@reach/router'; const Layout = ({ children }) => { const location = useLocation(); useEffect(() => { // 指定需要加载FullStory的页面路径 const allowedPaths = ['/blog', '/products']; if (allowedPaths.some(path => location.pathname.startsWith(path))) { const script = document.createElement('script'); script.src = 'https://edge.fullstory.com/s/fs.js'; script.async = true; script.dataset.fullstoryOrg = '你的FullStory组织ID'; document.body.appendChild(script); } }, [location.pathname]); return <div>{children}</div>; }; export default Layout;
2. 利用Gatsby Script组件优化加载时机(Gatsby v4+)
Gatsby v4及以上提供的<Script>组件支持多种加载策略,可延迟脚本加载,避免阻塞首屏渲染,同时按需加载减少未使用脚本问题。
示例代码:
import { Script } from 'gatsby'; import { useLocation } from '@reach/router'; const Layout = ({ children }) => { const location = useLocation(); // 判断当前页面是否需要加载FullStory const shouldLoad = ['/blog', '/products'].some(path => location.pathname.startsWith(path)); return ( <div> {children} {shouldLoad && ( <Script src="https://edge.fullstory.com/s/fs.js" async data-fullstory-org="你的FullStory组织ID" strategy="lazyOnload" // 页面加载完成后再加载脚本 /> )} </div> ); }; export default Layout;
3. 排除特定页面的插件注入(保留插件的前提下)
如果不想卸载gatsby-plugin-fullstory,可通过修改页面上下文,在非目标页面跳过脚本注入。
第一步:在gatsby-node.js中标记需排除的页面
exports.onCreatePage = ({ page, actions }) => { const { createPage } = actions; // 定义不需要FullStory的页面路径 const excludedPaths = ['/', '/about']; if (excludedPaths.includes(page.path)) { page.context.excludeFullStory = true; createPage(page); } };
第二步:在gatsby-browser.js中控制注入逻辑
import React from 'react'; import FullStory from 'gatsby-plugin-fullstory'; export const wrapPageElement = ({ element, pageContext }) => { // 若页面标记了排除,则不渲染FullStory组件 if (pageContext.excludeFullStory) { return element; } return ( <> <FullStory /> {element} </> ); };
缓存问题优化建议
虽然无法直接控制FullStory服务器的缓存策略,但可通过以下方式缓解:
- 确保脚本使用
async或defer属性加载,避免阻塞页面渲染; - 在需要加载脚本的页面添加预加载标签,提前获取脚本资源:
<link rel="preload" href="https://edge.fullstory.com/s/fs.js" as="script">
内容的提问来源于stack exchange,提问作者Vladan Mikic
相关产品推荐
相关产品推荐

