Blazor
延迟加载
延迟加载
当引用了其他具有页面的程序集时,默认会在进入页面的时候,加载对应的程序集。
假如程序集过大或者过多,首次加载会很慢,影响用户体验
微软提供了延迟加载的实现,配置如下:
1、首先你的项目要引用这个程序集
2、在Program.cs 注入后面用到的LazyAssemblyLoader
builder.Services.AddScoped<LazyAssemblyLoader>();
3、将程序集在项目文件中指定为延迟加载项目
<ItemGroup>
<BlazorWebAssemblyLazyLoad Include="Test-Blazor-Lib.dll" />
</ItemGroup>
4、在App.razor中指定Router的OnNavigateAsync
@using System.Reflection;
@using Microsoft.Extensions.Logging
@using Microsoft.AspNetCore.Components.WebAssembly.Services
@inject LazyAssemblyLoader AssemblyLoader
@inject ILogger<App> Logger
<Router AppAssembly="@typeof(Program).Assembly"
AdditionalAssemblies="@lazyLoadedAssemblies"
OnNavigateAsync="@OnNavigateAsync">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(BasicLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(BasicLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
<AntContainer />
@code{ private List<Assembly> lazyLoadedAssemblies = new List<Assembly>();
private async Task OnNavigateAsync(NavigationContext args)
{
try
{
Console.WriteLine($"Path: {args.Path}");
if (args.Path == "test/index")
{
var assemblies = await AssemblyLoader.LoadAssembliesAsync(
new[] { "Test-Blazor-Lib.dll" });
lazyLoadedAssemblies.AddRange(assemblies);
}
}
catch (Exception ex)
{
Logger.LogError("Error: {Message}", ex.Message);
}
}}