Maximizing Application Performance with Blazor's Lazy Loading
Written on
Chapter 1: Introduction to Lazy Loading in Blazor
In this article, we will explore how to implement Lazy Loading using Blazor WebAssembly, which allows us to defer the loading of resources that are not immediately necessary. This approach significantly improves the startup performance of your Blazor WebAssembly application. For instance, if users only need access to the home or contact pages, downloading all associated files for products and authentication becomes unnecessary. With Lazy Loading activated, resources will only be fetched when explicitly requested by the user.
Prerequisites
- SDK: .NET 6.0
- IDE: Visual Studio 2022
Setting Up Your Blazor WASM Project
Begin by launching Visual Studio and searching for "Blazor App." Click the Next button to proceed.
Define your project name, path, and solution name, then click the Create button. A new window will appear; ensure you select the target framework (.NET 6.0) and confirm that "Configure the Https" option is checked in the Advanced section.
Blazor WASM Standard Workflow
Once the application starts, open the Developer Tools window (F12) and navigate to the Application tab to inspect the cache. You will notice that the BlazorWasmLazyLoading.dll file has been downloaded and cached. While this is standard behavior, it indicates that all components within this DLL have been loaded, even though users remain on the Home page and have not yet navigated elsewhere. This might not be an issue for smaller applications, but for larger ones, it could drastically slow down download speeds. Therefore, let's examine how to optimize this process.
Adding Required Packages to Your Main Project
In this guide, we will utilize the Syncfusion Libraries to facilitate the Lazy Loading concept. Create a new Razor class library project named "Weather," and delete all contents except for the _Imports.razor file. Remember to reference this project from the main application.
Right-click on the project and select Manage NuGet Packages. Search for "Syncfusion.Blazor" and install the relevant Syncfusion.Blazor NuGet packages. The application will utilize the Blazor Buttons and Syncfusion.Blazor.Calendars packages.
Configuring the Syncfusion Blazor Service
In the Program.cs file, configure the Syncfusion Blazor service with the following code:
using LazyLoading;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Syncfusion.Blazor;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add("#app");
builder.RootComponents.Add("head::after");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddSyncfusionBlazor();
await builder.Build().RunAsync();
Implementing Lazy Loading
To activate Lazy Loading in your Blazor WebAssembly project, make an adjustment to the main project file. Right-click on the BlazorWasmLazyLoading project and select Edit Project File.
Modifying the App.razor File for DLL Loading
To import the necessary components, include the required using directives and inject the AssemblyLoader. The OnNavigateAsync method is linked to the OnNavigateAsync event callback within the Router component. This callback is executed prior to navigating to a new page. Additionally, set the AdditionalAssemblies property to true to instruct the application to load components from the specified URIs using extra assemblies.
Create a private list of assemblies called _lazyLoadedAssemblies in the @code section along with the OnNavigateAsync method that takes a NavigationContext parameter. This context allows us to verify the currently required route. If the route matches, the LoadAssembliesAsync method is invoked to load the necessary assemblies.
@using System.Reflection;
@using Microsoft.AspNetCore.Components.Routing;
@using Microsoft.AspNetCore.Components.WebAssembly.Services;
@inject LazyAssemblyLoader assemblyLoader;
@code {
private List lazyLoadedAssemblies = new List();
private async Task OnNavigateAsync(NavigationContext args)
{
try
{
if (args.Path.StartsWith("fetchdata"))
{
var assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Sample.dll" });
// Load additional assemblies as needed
lazyLoadedAssemblies.AddRange(assemblies);
}
if (args.Path.StartsWith("counter"))
{
var assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Syncfusion.Blazor.Calendars.dll" });
// Load additional assemblies as needed
lazyLoadedAssemblies.AddRange(assemblies);
}
}
catch (Exception ex)
{
// Handle exceptions}
}
}
Upon launching the app and inspecting the cache, the Sample.dll will not be immediately visible. However, once you navigate to the FetchData page, both the content and the dependencies that have been downloaded will be visible.
The first video, "Lazy Loading in Blazor WebAssembly," provides an overview of the lazy loading process in Blazor applications, showcasing its benefits and implementation strategies.
Conclusion
At this point, you have learned how to utilize Lazy Loading in Blazor WebAssembly to load dependencies only when required. This feature is invaluable as it significantly reduces the loading time of your application.
That's all there is to it!
Source Code
Keep Learning…!