How Lazyloading In Blazor Can Increase Your Application Performance!

Introduction

In this article, we'll look at how to use Blazor WebAssembly to achieve Lazy Loading. By postponing the download of resources we don't need right now, we can increase the startup performance of our Blazor WebAssembly application. For instance, if we have a huge Blazor WebAssembly application and our consumers just want to see the home or contact pages, downloading all of the files related to products, authentication, and so on is pointless. With lazy loading enabled, the program will only download these resources when the user specifically requests them.

Prerequisites

  • SDK - .Net 6.0
  • IDE - Visual Studio 2022

Blazor WASM Project Setup

Open the Visual Studio and search for Blazor App. Click on the Next button,

Define the project name, path, and solution name. Click on the Create button,

After that a new window will pop up to choose the target framework (.Net 6.0) from the dropdown and make sure to select the Blazor server App and in the Advanced section "Configure the Https" is checked.

How Lazyloading In Blazor Can Increase Your Application Performance

Blazor Wasm Standard Workflow

Now, if we start our application, open the Dev Tools window (F12), navigate to the Application tab, and inspect the cache:

How Lazyloading In Blazor Can Increase Your Application Performance

We can see that our BlazorWasmLazyLoading.dll file has been downloaded and cached, which is typical, but it also implies that all of the components in this DLL have been downloaded, despite the fact that we are still on the Home page and have not navigated anywhere else. Of course, this isn't an issue for little apps like this one. However, for a larger application, it could greatly enhance download speed. So, let's figure out how to avoid it.

Adding new packages to the main project

Here in this article, we are going to use the Syncfusion Libraries to work with the lazy loading concept and create a new Razor class library project, name it Weather, and remove everything inside it except the _Imports.razor file. Also, we have to reference this project from the main one.

Select Manage NuGet Packages from the project's right-click menu.
Then, using the keyword Syncfusion. Blazor, find, and install the appropriate Syncfusion.Blazor. NuGet packages from Blazor. We've deployed Syncfusion in this location. The programme uses the NuGet packages Blazor. Buttons and Syncfusion.Blazor.Calendars. Take a look at the image below.

How Lazyloading In Blazor Can Increase Your Application Performance

Configure the Syncfusion Blazor Service in Program.cs file as per the below code.

Program.cs

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>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddSyncfusionBlazor();

await builder.Build().RunAsync();

Implementation of the Lazy Loading

To implement Lazy Loading in Blazor WebAssembly, we must first make a change to the main project file. So, right-click on the BlazorWasmLazyLoading project and select EditProjectFile from the context menu:

LazyLoading.csproj

<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="6.0.1" />
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="6.0.1" PrivateAssets="all" />
    <PackageReference Include="Syncfusion.Blazor.Buttons" Version="19.4.0.48" />
    <PackageReference Include="Syncfusion.Blazor.Calendars" Version="19.4.0.48" />
    <PackageReference Include="Syncfusion.Blazor.Charts" Version="19.4.0.48" />
    <PackageReference Include="Syncfusion.Blazor.Data" Version="19.4.0.48" />
    <PackageReference Include="Syncfusion.Blazor.DropDowns" Version="19.4.0.48" />
    <PackageReference Include="Syncfusion.Blazor.Grid" Version="19.4.0.48" />
    <PackageReference Include="Syncfusion.Blazor.Lists" Version="19.4.0.48" />
    <PackageReference Include="Syncfusion.Blazor.Navigations" Version="19.4.0.48" />
    <PackageReference Include="Syncfusion.Blazor.Notifications" Version="19.4.0.48" />
    <PackageReference Include="Syncfusion.Blazor.Popups" Version="19.4.0.48" />
    <PackageReference Include="Syncfusion.Blazor.Spinner" Version="19.4.0.48" />
    <PackageReference Include="Syncfusion.Blazor.SplitButtons" Version="19.4.0.48" />
  </ItemGroup>
	<ItemGroup>
		<BlazorWebAssemblyLazyLoad Include="Syncfusion.Blazor.Buttons.dll" />
		<BlazorWebAssemblyLazyLoad Include="Syncfusion.Blazor.Calendars.dll" />
		<BlazorWebAssemblyLazyLoad Include="Syncfusion.Blazor.Charts.dll" />
		<BlazorWebAssemblyLazyLoad Include="Syncfusion.Blazor.Data.dll" />
		<BlazorWebAssemblyLazyLoad Include="Syncfusion.Blazor.DropDowns.dll" />
		<BlazorWebAssemblyLazyLoad Include="Syncfusion.Blazor.Grids.dll" />
		<BlazorWebAssemblyLazyLoad Include="Syncfusion.Blazor.Lists.dll" />
		<BlazorWebAssemblyLazyLoad Include="Syncfusion.Blazor.Navigations.dll" />
		<BlazorWebAssemblyLazyLoad Include="Syncfusion.Blazor.Notifications.dll" />
		<BlazorWebAssemblyLazyLoad Include="Syncfusion.Blazor.Popups.dll" />
		<BlazorWebAssemblyLazyLoad Include="Syncfusion.Blazor.Spinner.dll" />
		<BlazorWebAssemblyLazyLoad Include="Syncfusion.Blazor.SplitButtons.dll" />
	</ItemGroup>
	<ItemGroup>
	  <ProjectReference Include="..\Sample\Sample.csproj" />
	</ItemGroup>
	<ItemGroup>
		<BlazorWebAssemblyLazyLoad Include="Sample.dll" />
	</ItemGroup>
</Project>

Modifying App.razor File to Load the Required DLL

To load our assembly, we first import the needed utilizing directives and inject the AssemblyLoader. The OnNavigateAsync method is then assigned to the OnNavigateAsync event callback in the Router component. Before moving to a new page, the OnNavigateAsync event callback is called. We also set the AdditionalAssemblies property to true. This attribute instructs our program to look for components that match the appropriate URIs using additional assemblies.

We establish a private list of assemblies called _lazyLoadedAssemblies in the @code section, as well as the OnNavigateAsync method with the NavigationContext parameter. We use the context argument to check the currently necessary route inside the procedure. We utilize the LoadAssembliesAsync method to load assemblies if it matches the fetch data route, which is the route of our FetchData component.

App.razor

@using System.Reflection;
@using Microsoft.AspNetCore.Components.Routing;
@using Microsoft.AspNetCore.Components.WebAssembly.Services;
@inject LazyAssemblyLoader assemblyLoader;
<Router AppAssembly="@typeof(App).Assembly" PreferExactMatches="@true" AdditionalAssemblies="@lazyLoadedAssemblies" OnNavigateAsync="@OnNavigateAsync">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

@code {
    private List<Assembly> lazyLoadedAssemblies = new List<Assembly>();
    private async Task OnNavigateAsync(NavigationContext args)
    {
        try
        {
            if (args.Path.StartsWith("fetchdata"))
            {
                var assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Sample.dll" });
                assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Syncfusion.Blazor.Buttons.dll" });
                assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Syncfusion.Blazor.Charts.dll" });
                assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Syncfusion.Blazor.Data.dll" });
                assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Syncfusion.Blazor.DropDowns.dll" });
                assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Syncfusion.Blazor.Grid.dll" });
                lazyLoadedAssemblies.AddRange(assemblies);
            }
            if(args.Path.StartsWith("counter"))
            {
                var assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Syncfusion.Blazor.Calendars.dll" });
                assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Syncfusion.Blazor.Buttons.dll" });
                assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Syncfusion.Blazor.Lists.dll" });
                assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Syncfusion.Blazor.Navigations.dll" });
                assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Syncfusion.Blazor.Notifications.dll" });
                assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Syncfusion.Blazor.Popups.dll" });
                assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Syncfusion.Blazor.Spinner.dll" });
                assemblies = await assemblyLoader.LoadAssembliesAsync(new[] { "Syncfusion.Blazor.SplitButtons.dll" });
                lazyLoadedAssemblies.AddRange(assemblies);
            }
        }
        catch (Exception ex)
        {

        }
    }
}

Remember that if we launch the app and look through the cache, we won't be able to identify the Sample.dll that was downloaded. However, when we go to the FetchData page, we can see the page's content as well as the dependencies that have been downloaded and the same for the counter page as well.

How Lazyloading In Blazor Can Increase Your Application Performance

Counter page

How Lazyloading In Blazor Can Increase Your Application Performance

Conclusion

Right now, we know how to use Blazor WebAssembly's Lazy Loading to load different dependencies only when we need them. As previously stated, this is a fantastic feature because it helps us to reduce the time it takes for our application to load.

That’s all there is to it!

Source Code - GItHub

Keep Learning.....!


Similar Articles