Pre-render Blazor application using web assembly


Isn't it fun,

to instantly listen to a blog on the go? PLAY !

 
 

Blazor-application

The initial load time is the biggest drawback of using Blazor assembly application. Web assembly allows the developer to use the serverless deployment scenario and fast interaction.

The initial download can take time. Browser download all runtime and project's DLL. Pre-rendering is the default for server-side applications and also client-side applications can use pre-rendering.

Table of Content

What is pre-rendering?

Pre-rendering is the process where all HTML elements of the web page are compiled on the server and static HTML is served as output to the client. Pre-rendering helps to improve SEO (Search Engine Optimisation) of SPAs (Single Page Applications). Using the pre-rendering website load much faster. Without pre-rendering Blazor web, assembly parses the index.html file and then fetches all dependency, and then it will load the lunch application.Pre-rendering is used to render UI components to the server in the response to the first request.

Pre-rendering means a Pre-rendering component which is done by integrating the application using razor pages.

When a user request for page requested page will be built on the server and compiled to static HTML. In the client-side Blazor application,static HTML will include the blazor.webassembly.js file.

Without pre-rendering client receive static HTML which will be rendered and process as normal.

Figure-1 Blazor Application

The Pre-rendering Tread-off

Using pre-rendering, the developer will no longer deploy Blazor application as a static HTML file.

.NET run-time is required because pre-rendering requires razor pages. For Pre-rendering, developer must manage JavaScript call to account is another trade-off.

If develops attempt to perform JavaScript interop in onInit or OnInitAsnc method of rendered component then it will throw an exception.When pre-rendering is used thenOnAfterRenderAsync method is called after page is fully rendered and all javaall JavaScript interop calls are moved to this method.

Pre-render your application step by step

To create Blazor web Application follow the below steps:

Step 1: Create an application.

Open Visual studio.

Go to File manager ->project.

Create a new Blazor project with the "BlazorDemo” name and click on the Create button.

Figure-2Create Blazor application

Step 2: Select Template.

Select Blazor Web Assembly Application template and click on the Create button.

Figure-3 Select Web Assembly App template.


Your application has three projects:

BlazorDemo.Client: Project define all Blazor web assembly component

BlazorDemo.Server: BlazorDemo.Server project Server client project to the browser.

BlazorDemo.Shared

For Pre-rendering client application index.html file from BlazorDemo.Client/wwwroot is used, instead of that, we are going to. cshtml file in BlazorDemo.Server project to load the client application.

Step 3: Set up _Host file.

Create _Host.cshtml file in the Pages folder in the BlazorDemo.Server project.

BlazorDemo.Server\Pages\_Host.cshtml

BlazorDemo.Server \ Pages \ _Host.cshtml
@page
@usingBlazorDemo.Client
<!doctypehtml><html><head>
<metacharset="utf-8"/>
<metaname="viewport"content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/><title></title></head><body>
<app>

</app>

<scriptsrc="_framework/blazor.webassembly.js"></script></body></html>

</!doctypehtml>

Component tag helper is used to pre-rendering in Blazor server app. Blazor server project template by default pre-render entire app form Page / _Host.cshtml using component tag helper.

Component tag helper is used to render specifiedBlazor components into a page or view.

Also, Blazor web assembly application allows the developer to use component tag helper with new render mode and add multiple components to pages and view.

We can also pass the parameter to component tag helper using web assembly render mode and the parameter must be serialized.

Example:

<!doctypehtml>
<component param-incrementamount="6" render-mode="WebAssemblyPrerendered" type="typeof(Counter)" />
</!doctypehtml>

Component tag helper have following rendering mode:

Server pre-rendered: Server pre-rendered is used to pre-render component into static HTML and to include blazor server app to later use to make component interactive when loaded into browser.

Server: Server is used to include blazor server app to include interactive component when loaded in browser without pre-rendering.

Static: Static is used to render components into static HTML which is not interactive.

In .NET 5 support two more additional rendering mode:

Web Assembly Pre-rendered:Web Assembly Pre-rendered is used to pre-render components into static HTML and use blazor web assembly to make components interactive when loaded into the browser.

Web Assembly: Web Assembly is used to render component into static HTML and use blazor web assembly to make component interactive when loaded into the browser without Pre-rendering.

Step 4: Configuring Host.

In BlazorDemo.Server, in Startup.cs file and update configure method to following:

usingMicrosoft.AspNetCore.Builder;
usingMicrosoft.AspNetCore.Hosting;
usingMicrosoft.AspNetCore.HttpsPolicy;
usingMicrosoft.AspNetCore.ResponseCompression;
usingMicrosoft.Extensions.Configuration;
usingMicrosoft.Extensions.DependencyInjection;
usingMicrosoft.Extensions.Hosting;
usingSystem.Linq;

namespaceBlazorDemo.Server
{
publicclassStartup
    {
publicStartup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

publicIConfiguration Configuration { get; }
publicvoidConfigureServices(IServiceCollection services)
        {

services.AddControllersWithViews();
services.AddRazorPages();
        }
publicvoidConfigure(IApplicationBuilder app, IWebHostEnvironmentenv)
        {
if (env.IsDevelopment())
            {
app.UseDeveloperExceptionPage();
app.UseWebAssemblyDebugging();
            }
else
            {
app.UseExceptionHandler("/Error");
app.UseHsts();
            }

app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();

app.UseRouting();

app.UseEndpoints(endpoints =>
            {
endpoints.MapRazorPages();
endpoints.MapControllers();
//endpoints.MapFallbackToFile("index.html");
endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}

When the developer attempt to navigate page request will be direct to _Host.cshtml which will render the component and return static HTML.


Looking to hire ASP.Net Development Company in USA ?

Your Search ends here.


In the IApplicationBuilder interfaceuse app.UseBlazorFrameworkFiles(); which is used to server blazor web assembly files from the specified path.

MapFallbackToPage() serve _Host.cshtml file in BlazorDemo.Server project.

Step 5: Enable Tag helper.

Tag helper is used to modify mark-up which gets return to browser.

Component tag helper renders HTML for blazor web assembly application.

Add _ViewImports.cshtml file to BlazorDemo.Server inside page folder as follow:

@usingBlazorDemo.Server
@namespaceBlazorDemo.Server.Pages
@addTagHelper*,Microsoft.AspNetCore.Mvc.TagHelpers

Step 6: Run the application.

Run again and you get blazor project template.

Figure-4Run application

When the blazor.webassembly.js file is executed then runtime is downloaded with application dll and your application will be run. At that time pre-render static element is replaced by an interactive component.

Test Pre-rendering

Run application and the easiest way to test pre-rendering are to disable JavaScript in your browser.

Press CTR+SHIFT+P and disable JavaScript if the page is loaded then pre-rendering is working.

Figure-5Disable JavaScript

Conclusion

Pre-rendering is a really useful tool to use it with both server and client-side blazor application. In this blog, we worked through how to pre-render our blazor web assembly application for example. Pre-rendering overcomes the initial load time drawback of blazor web assembly application.

Pre-render Blazor application using web assembly

Component tag helper is used to pre-rendering in Blazor server app. Blazor server project template by default pre-render entire app form Page / _Host.cshtml using component tag helper.

Component tag helper is used to render specifiedBlazor components into a page or view.

Also, Blazor web assembly application allows the developer to use component tag helper with new render mode and add multiple components to pages and view.

We can also pass the parameter to component tag helper using web assembly render mode and the parameter must be serialized.

Example:

<!doctypehtml>
<component param-incrementamount="6" render-mode="WebAssemblyPrerendered" type="typeof(Counter)" />
</!doctypehtml>

Component tag helper have following rendering mode:

Server pre-rendered: Server pre-rendered is used to pre-render component into static HTML and to include blazor server app to later use to make component interactive when loaded into browser.

Server: Server is used to include blazor server app to include interactive component when loaded in browser without pre-rendering.

Static: Static is used to render components into static HTML which is not interactive.

In .NET 5 support two more additional rendering mode:

Web Assembly Pre-rendered:Web Assembly Pre-rendered is used to pre-render components into static HTML and use blazor web assembly to make components interactive when loaded into the browser.

Web Assembly: Web Assembly is used to render component into static HTML and use blazor web assembly to make component interactive when loaded into the browser without Pre-rendering.

Step 4: Configuring Host.

In BlazorDemo.Server, in Startup.cs file and update configure method to following:

usingMicrosoft.AspNetCore.Builder;
usingMicrosoft.AspNetCore.Hosting;
usingMicrosoft.AspNetCore.HttpsPolicy;
usingMicrosoft.AspNetCore.ResponseCompression;
usingMicrosoft.Extensions.Configuration;
usingMicrosoft.Extensions.DependencyInjection;
usingMicrosoft.Extensions.Hosting;
usingSystem.Linq;

namespaceBlazorDemo.Server
{
publicclassStartup
    {
publicStartup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

publicIConfiguration Configuration { get; }
publicvoidConfigureServices(IServiceCollection services)
        {

services.AddControllersWithViews();
services.AddRazorPages();
        }
publicvoidConfigure(IApplicationBuilder app, IWebHostEnvironmentenv)
        {
if (env.IsDevelopment())
            {
app.UseDeveloperExceptionPage();
app.UseWebAssemblyDebugging();
            }
else
            {
app.UseExceptionHandler("/Error");
app.UseHsts();
            }

app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();

app.UseRouting();

app.UseEndpoints(endpoints =>
            {
endpoints.MapRazorPages();
endpoints.MapControllers();
//endpoints.MapFallbackToFile("index.html");
endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}

When the developer attempt to navigate page request will be direct to _Host.cshtml which will render the component and return static HTML.


Looking to hire ASP.Net Development Company in USA ?

Your Search ends here.


In the IApplicationBuilder interfaceuse app.UseBlazorFrameworkFiles(); which is used to server blazor web assembly files from the specified path.

MapFallbackToPage() serve _Host.cshtml file in BlazorDemo.Server project.

Step 5: Enable Tag helper.

Tag helper is used to modify mark-up which gets return to browser.

Component tag helper renders HTML for blazor web assembly application.

Add _ViewImports.cshtml file to BlazorDemo.Server inside page folder as follow:

@usingBlazorDemo.Server
@namespaceBlazorDemo.Server.Pages
@addTagHelper*,Microsoft.AspNetCore.Mvc.TagHelpers

Step 6: Run the application.

Run again and you get blazor project template.

Figure-4Run application

When the blazor.webassembly.js file is executed then runtime is downloaded with application dll and your application will be run. At that time pre-render static element is replaced by an interactive component.

Test Pre-rendering

Run application and the easiest way to test pre-rendering are to disable JavaScript in your browser.

Press CTR+SHIFT+P and disable JavaScript if the page is loaded then pre-rendering is working.

Figure-5Disable JavaScript

Conclusion

Pre-rendering is a really useful tool to use it with both server and client-side blazor application. In this blog, we worked through how to pre-render our blazor web assembly application for example. Pre-rendering overcomes the initial load time drawback of blazor web assembly application.