In this lesson, you will learn how to shrink your Blazor WebAssembly payload by deferring the loading of heavy assemblies and pruning unused code during compilation.
When a user opens your Blazor WebAssembly app, they download a collection of .NET assemblies. As your project grows, this "initial load" time increases, potentially harming user retention. We solve this using two primary strategies: Lazy Loading and Linker Configuration.
Lazy Loading Assemblies
Instead of forcing the browser to download every library at startup, you can tell Blazor to load specific assemblies only when they are actually needed. First, identify large assemblies (like those used for PDF generation or complex data visualization) and mark them as lazy in your .csproj file:
<ItemGroup>
<BlazorWebAssemblyLazyLoad Include="LargeReportLibrary.dll" />
</ItemGroup>
Then, use the LazyAssemblyLoader service in your component to fetch the assembly dynamically when a user navigates to the relevant page:
@inject Microsoft.AspNetCore.Components.WebAssembly.Services.LazyAssemblyLoader AssemblyLoader
@code {
private async Task LoadDependencies() {
var assemblies = await AssemblyLoader.LoadAssembliesAsync(new[] { "LargeReportLibrary.dll" });
// Now you can use types from the library!
}
}
Configuring the Linker
Blazor uses the Intermediate Language (IL) Linker to trim unused code from your dependencies. By default, the linker is set to link mode for release builds. You can control the aggressiveness of this pruning in your .csproj to further reduce your bundle size:
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<PublishTrimmed>true</PublishTrimmed>
<TrimMode>link</TrimMode>
</PropertyGroup>
If you notice that some code is being removed that is actually accessed via Reflection, you can prevent specific assemblies from being trimmed by adding them to your project file:
<ItemGroup>
<TrimmerRootAssembly Include="ThirdPartyLibraryThatUsesReflection" />
</ItemGroup>
By combining these techniques, you ensure that the browser only processes the bare minimum code required to render your initial landing page, while the rest of your logic stays tucked away until the user specifically triggers it.
Key Takeaway: Optimize your delivery by prioritizing the initial load through lazy loading, while letting the IL Linker aggressively prune unused code from your deployment payload.