Blazor WASM PWA可以通过懒加载模块来减少Javascript代码的大小和首次加载时间。使用Blazor WASM PWA的时候,可以使用以下代码示例来实现懒加载模块:
首先,在blazor.boot.json文件中指定需要懒加载的模块:
{
"configurations": {
"LazyLoading": [
"app.lazy.js"
]
},
"resources": {
"lazy": [
{
"type": "module",
"path": "app.lazy.dll",
"cdnBase": ""
}
]
}
}
然后,在Startup类中将LazyLoading配置传递到Server服务中:
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseLazyLoading(new LazyLoadingOptions()
{
ConfigurationSectionName = "LazyLoading"
});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapFallbackToFile("index.html");
});
最后,创建一个空的Blazor项目模块(例如,叫做Components),添加一个LazyLoadingComponent类到该模块中:
namespace Components
{
public class LazyLoadingComponent : ComponentBase
{
}
}
现在,可以通过以下代码在MainLayout组件中懒加载Components模块:
@using Microsoft.AspNetCore.Components.LazyLoading
404
The page you are looking for could not be found.
@inject ILazyLoader LazyLoader
@if (_showLazyComponent)
{