Blazor WASM Lazy Loading

Blazor WASM Lazy Loading


24 Articles


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.

Table of Contents

  1. What is Lazy Loading and Why it is needed?
  2. How to implement Lazy loading?
  3. Summary

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.

Notice that in the network tab only necessary items to load home page will be requested.

Home screen of I Love Dotnet

Now on navigating to Blazor Wasm Lazy Loading article, Notice that in the network tab and will be requested.

Lazy Loading of Blazor Demo Components


I'm happy that you have reached to the end of this article. We learnt what is lazy loading and why it is needed and how to configure lazy loading in blazor wasm applications. All these can be validated from network tab of your browser inside i love dotnet site.

  • Blazor
  • Lazy Loading