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

.NET 9 Blazor应用启动时如何显示加载进度?

解决.NET 9 Blazor Web应用启动空白页+加载界面无效问题

核心问题原因

你之前的方案依赖Blazor组件(比如SplashLayout)显示加载界面,但Blazor框架本身需要时间初始化,这段时间浏览器只会显示空白的index.html,导致加载界面根本没机会在启动初期展示。必须让加载内容在HTML层面直接渲染,完全不依赖Blazor的初始化流程。

具体解决步骤

1. 在index.html中直接嵌入加载界面(关键步骤)

打开wwwroot/index.html,在<body>内的Blazor挂载容器(通常是<div id="app">)中直接添加加载界面的HTML和样式,确保页面一加载就显示:

<body>
    <!-- 加载界面:放在Blazor挂载容器内,Blazor初始化完成后会自动替换容器内内容 -->
    <div id="app">
        <div class="splash-screen">
            <div class="loader"></div>
            <p>正在初始化应用,请稍候</p>
        </div>
    </div>

    <script src="_framework/blazor.web.js"></script>
</body>

同时在<head>标签内添加全屏覆盖的样式:

<style>
    .splash-screen {
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        background-color: #fff;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    }

    .loader {
        border: 8px solid #f3f3f3;
        border-top: 8px solid #2563eb;
        border-radius: 50%;
        width: 60px;
        height: 60px;
        animation: spin 1.5s linear infinite;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
</style>

2. 初始化完成后自动移除加载界面

不需要依赖组件的OnAfterRenderAsync,直接通过Blazor的启动完成事件移除加载界面,逻辑更可靠:
在index.html的Blazor脚本标签后添加以下JS代码:

<script>
    Blazor.start().then(() => {
        const splash = document.querySelector('.splash-screen');
        if (splash) {
            // 添加淡出动画提升体验
            splash.style.transition = 'opacity 0.5s';
            splash.style.opacity = '0';
            setTimeout(() => splash.remove(), 500);
        }
    });
</script>

3. 清理无效的旧方案

  • 删除之前创建的SplashLayout.razor(如果无其他场景使用)
  • 移除组件中用于移除加载界面的OnAfterRenderAsync相关逻辑
  • 清理之前添加的splash-screen相关Blazor包或配置

额外优化建议

  • 如果应用需要加载大量静态资源(如JS、CSS),可以通过监听document.onload事件结合资源加载统计,在加载界面显示实时进度
  • 可自定义加载界面样式,比如添加应用Logo、品牌色,让体验更贴合产品风格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 07:27:05