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

如何为Gatsby.js站点添加加载页面以优化首次加载体验?

解决Gatsby首次访问资源加载卡顿的加载页实现方案

1. 先写一个加载页组件

在src/components下新建Loading.js和对应的样式文件:

// src/components/Loading.js
import React from 'react';
import './Loading.css';

const Loading = () => {
  return (
    <div className="loading-container">
      <div className="loading-spinner"></div>
      <p>加载中...</p>
    </div>
  );
};

export default Loading;
/* src/components/Loading.css */
.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #fff; /* 替换成你的网站主背景色 */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999; /* 确保在所有内容上方 */
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid #eee;
  border-top-color: #2c3e50; /* 替换成你的主题色 */
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

2. 全局控制加载逻辑

在项目根目录新建或修改gatsby-browser.js,用它来包裹整个应用,控制加载页的显示时机:

// gatsby-browser.js
import React, { useState, useEffect } from 'react';
import Loading from './src/components/Loading';

export const wrapRootElement = ({ element }) => {
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const finishLoading = () => {
      // 加个小延迟,避免加载页闪一下就消失,体验更流畅
      setTimeout(() => setIsLoading(false), 800);
    };

    // 如果页面已经加载完成(比如刷新后),直接结束加载
    if (document.readyState === 'complete') {
      finishLoading();
    } else {
      // 监听所有资源加载完成事件
      window.addEventListener('load', finishLoading);
      // 组件卸载时移除监听
      return () => window.removeEventListener('load', finishLoading);
    }
  }, []);

  return isLoading ? <Loading /> : element;
};

3. 额外优化建议(减少卡顿根源)

  • 图片用gatsby-plugin-image处理,它会自动生成适配不同设备的图片格式,还支持懒加载,大幅降低首次加载压力。
  • 给有过渡效果的元素加will-change: transform;,让浏览器提前为动画分配资源,减少卡顿。
  • 把核心CSS内联到HTML头部,避免样式闪烁,Gatsby可以用gatsby-plugin-inline-css插件实现。

4. 测试验证

运行gatsby develop启动项目,首次访问时加载页会停留到所有资源加载完成(加了延迟),之后刷新或跳转页面,因为资源已经缓存,加载页会快速关闭,不会影响体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 20:22:49