Blazor WASM Lazy Loading
Blazor
29 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.
Note: If you have not done so already, I recommend you read the article on Blazor WASM Error Logging.
Table of Contents
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. This will be more useful in micro-frontends
where each micro-frontend is a
Blazor WASM application.
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.
Project file configuration
- First we need to find the components to be lazy loaded and move them to new assembly
(Razor Class Library Project)
. - Next refer this
new assembly
in the Blazor WASM project. - Finally add the assembly name with
.wasm
extension in the Blazor WASM.csproj
usingBlazorWebAssemblyLazyLoad
. - 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
- Go to
App.razor
file. - Import
@using Microsoft.AspNetCore.Components.WebAssembly.Services
. - Inject
@inject LazyAssemblyLoader AssemblyLoader
- In
Router
component, assignOnNavigateAsync="@OnNavigateAsync"
. This event gets triggered whenever we navigate to new page. - Now you can conditionally
lazy load asssemblies
based on route usingawait AssemblyLoader.LoadAssembliesAsync(new[] { "Components.wasm" });
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.
Now on navigating to Blazor Wasm Lazy Loading article, Notice that in the network tab BaseComponents.wasm.br
and
BlazorDemoComponents.wasm.br
will be requested.
Summary
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. This will benefit a lot in micro-frontend
architecture. All these can be validated from network tab
of your browser inside
i love dotnet
site.