Lazy loading Blazor WebAssembly assemblies

We can set our WebAssembly application to lazy load assemblies thus reducing the initial download of files.

For example if you have parts of your application that are rarely used, you could ensure these parts exist within their own (or shared) assembly and then set the project up to lazy load them when required. We simply make these changes to the csproj file

<ItemGroup>
  <BlazorWebAssemblyLazyLoad Include="your-assembly.dll" />
</ItemGroup>

We can use the LazyAssemblyLoader service to download/load assemblies as required (don’t forget to register the LazyAssemblyLoader as a singleton), for example

@inject LazyAssemblyLoader AssemblyLoader

@code {
  private async Task OnNavigateAsync(NavigationContext args)
  {
    try 
    { 
       if (args.Path = = "{PATH}") 
       { 
         var assemblies = await AssemblyLoader.LoadAssembliesAsync( 
           new[] { {LIST OF ASSEMBLIES} }); } 
       } 
       catch (Exception ex) 
       { 
         Logger.LogError(" Error: {Message}", ex.Message); 
       } 
    }
  }
}