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

MudBlazor Server页面刷新时如何立即显示加载旋转器?

解决MudBlazor Server刷新页面时加载旋转器延迟显示的问题

问题根源

Blazor Server的ServerPrerendered模式下,刷新页面时浏览器需要等待服务器返回预渲染的HTML内容,这段时间页面会保持旧状态或空白,导致你当前的组件内旋转器要等服务器响应后才会显示,出现3秒左右的延迟。

解决方案

1. 添加客户端立即显示的静态加载动画

在_Host.cshtml中,Blazor组件加载前插入静态加载动画,让用户刷新页面瞬间就能看到反馈:

<body>
    <!-- 初始加载动画,刷新页面立即显示 -->
    <div id="initial-loader" style="position: fixed; inset: 0; background-color: rgba(0,0,0,0.5); display: flex; justify-content: center; align-items: center; z-index: 9999;">
        <div style="width: 50px; height: 50px; border: 4px solid #f3f3f3; border-top: 4px solid #6366f1; border-radius: 50%; animation: spin 1s linear infinite;"></div>
        <style>
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        </style>
    </div>

    <component type="typeof(App)" render-mode="ServerPrerendered" />

    <!-- Blazor初始化完成后隐藏静态加载动画 -->
    <script>
        window.addEventListener('blazorinitialized', () => {
            document.getElementById('initial-loader').style.display = 'none';
        });
    </script>

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

2. 优化MainLayout中的数据加载逻辑

避免在渲染时重复调用数据接口,改用异步初始化加载,减少渲染阻塞:

<MudMainContent>
    <MudContainer MaxWidth="MaxWidth.ExtraExtraLarge">
        @if (_departmentData?.DepartmentList is null || _jobData?.JobList is null || 
            _departmentData.DepartmentList.Count == 0 || _jobData.JobList.Count == 0)
        {
            <MudOverlay Visible="true" DarkBackground="true" ZIndex="9999">
                <MudProgressCircular Color="Color.Secondary" Indeterminate="true" />
            </MudOverlay>
        }
        else
        {
            @Body
        }           
    </MudContainer>
</MudMainContent>

@code {
    private DepartmentResponse? _departmentData;
    private JobResponse? _jobData;

    protected override async Task OnInitializedAsync()
    {
        // 异步加载数据,不阻塞组件初始渲染
        _departmentData = await _departments.GetDepartmentsAsync();
        _jobData = await _jobs.GetJobsAsync();
        StateHasChanged();
    }
}

补充说明

  • 静态加载动画会在Blazor完成初始化(触发blazorinitialized事件)后自动隐藏,无缝切换到组件内的旋转器(如果数据还未加载完成)。
  • 将数据加载逻辑移到OnInitializedAsync中,能让组件在初始化阶段就开始请求数据,进一步缩短等待时间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 00:22:20