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

Blazor预渲染WebAssembly应用中添加加载动画的方法

为Blazor WASM托管模式添加加载进度提示

方法1:基础加载遮罩(HTML+CSS+JS互操作)

在托管模式的_Host.cshtml中,围绕Blazor挂载点添加加载提示元素,配合样式实现全屏遮罩,待Blazor初始化完成后隐藏:

  1. 修改_Host.cshtml的挂载区域:
<div id="app">
    <!-- 服务器预渲染内容会填充到这里 -->
    <div id="loading-mask" class="loading-overlay">
        <div class="spinner"></div>
        <p>应用加载中,请稍候...</p>
    </div>
</div>

<script src="_framework/blazor.webassembly.js"></script>
  1. 添加全局CSS样式:
.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255,255,255,0.95);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    z-index: 9999;
}

.spinner {
    width: 48px;
    height: 48px;
    border: 4px solid #e0e0e0;
    border-top-color: #2196f3;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}
  1. 初始化完成后隐藏遮罩:
    在Program.cs中添加JS互操作代码:
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");

// 其他服务配置...

var host = builder.Build();
await host.RunAsync();
// Blazor初始化完成后隐藏加载遮罩
await host.Services.GetRequiredService<IJSRuntime>().InvokeVoidAsync("hideLoadingMask");

同时在_Host.cshtml中添加对应的JS函数:

function hideLoadingMask() {
    document.getElementById('loading-mask').style.display = 'none';
}

方法2:基于组件状态的加载提示

如果需要在Blazor组件内控制加载状态,可以在根组件App.razor中处理:

@inject IJSRuntime JSRuntime

@if (isLoading)
{
    <div class="loading-overlay">
        <div class="spinner"></div>
        <p>正在准备应用...</p>
    </div>
}
else
{
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
            <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        </Found>
        <NotFound>
            <PageTitle>Not found</PageTitle>
            <LayoutView Layout="@typeof(MainLayout)">
                <p role="alert">Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
}

@code {
    private bool isLoading = true;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // 等待Blazor完成所有初始化逻辑
            await Task.Delay(200);
            isLoading = false;
            StateHasChanged();
        }
    }
}

方法3:真实加载进度条

如果需要展示精准的资源加载进度,可以监听Blazor的资源加载事件:

在_Host.cshtml中添加进度条元素和监听脚本:

<div id="loading-mask" class="loading-overlay">
    <div class="progress-wrap">
        <div id="progress-bar" class="progress-bar"></div>
    </div>
    <p>加载资源中...(@loadedCount/@totalCount)</p>
</div>

<script>
    let loadedCount = 0;
    let totalCount = 20; // 预估核心资源数量,可根据实际调整

    window.updateProgress = () => {
        loadedCount++;
        const progress = (loadedCount / totalCount) * 100;
        document.getElementById('progress-bar').style.width = `${progress}%`;
        document.querySelector('.loading-overlay p').textContent = `加载资源中...(${loadedCount}/${totalCount})`;
    }

    Blazor.start({
        loadBootResource: (type, name, defaultUri) => {
            window.updateProgress();
            return defaultUri;
        }
    });
</script>

<script src="_framework/blazor.webassembly.js"></script>

对应的进度条CSS:

.progress-wrap {
    width: 70%;
    height: 6px;
    background: #e0e0e0;
    border-radius: 3px;
    margin-bottom: 12px;
}

.progress-bar {
    height: 100%;
    background: #2196f3;
    border-radius: 3px;
    width: 0%;
    transition: width 0.15s ease;
}

这些方案都能在Blazor初始化的1-2秒内提供明确的加载反馈,避免用户因界面无法交互产生困惑。可根据需求选择基础遮罩、组件内控制或精准进度条的实现方式。

内容的提问来源于stack exchange,提问作者Markus Strauß

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:01:12