Blazor WASM Lazy Loading

Blazor WASM Lazy Loading

blazor

20 Articles

Improve

In this article, let's learn about what is lazy loading, why it is needed and how to implement lazy loading in Blazor WASM application.

What is Lazy Loading and Why it is needed?

Lazy loading in Blazor WASM helps to defer downloading of assemblies until the route in which the assembly components used are requested by the end user. This helps to improve startup performance of large Blazor WASM applications

I ❤️ .NET makes use of lazy loading to load blog related components only when an blog is opened. It makes sense to not load all the components and assemblies when the user just visit the home screen. Thus saving startup time and saving user bandwidth by avoiding unnecessary downloads.

How to implement Lazy loading?

To implement lazy loading, we need to follow two steps.

  1. Project file configuration
  2. Router component configuration

Project file configuration

  1. First we need to find the components to be lazy loaded and move them to new assembly (Razor Class Library Project).
  2. Next refer this new assembly in the Blazor WASM project.
  3. Finally add the assembly name with .dll extension in the Blazor WASM .csproj using BlazorWebAssemblyLazyLoad.
  4. Repeat step 2 for as many assemblies to be lazy loaded.

Code Sample - Blazor WASM Lazy Loading Project File Configuration

This will make Blazor framework to prevent the assemblies to be loaded at app launch thus improves the performance.

Router component configuration

  1. Go to App.razor file.
  2. Import @using Microsoft.AspNetCore.Components.WebAssembly.Services.
  3. Inject @inject LazyAssemblyLoader AssemblyLoader
  4. In Router component, assign OnNavigateAsync="@OnNavigateAsync". This event gets triggered whenever we navigate to new page.
  5. Now you can conditionally lazy load asssemblies based on route using await AssemblyLoader.LoadAssembliesAsync(new[] { "Components.dll" });

Code Sample - Blazor WASM Lazy Loading Project File Configuration

Wow. We have completed lazy loading implementation in Blazor WASM application. Now that your Blazor WASM app will start up faster and lazy load assemblies on demand based on route thus increasing speed and saves user bandwidth.

  • Blazor
  • Lazy Loading