How to Prerender Title in Blazor without JavaScript

Posted 4 years ago by selliott
Edited 4 years ago
0

I recently ran across a blog post by Jimmy Engstrom at http://www.engstromjimmy.se/post/2020-03-11-ChangeTitle that explains most of the steps needed to get title tags to prerender in your page source (so search engines will see it). This is the post that lead me in the direction to eventually getting it working in BlazorForum.

The issue I was still running into had to do with the step of inserting the component into the _Host.cshml file. When the new component in the Head was loading before the main component that renders all the Body, it was prerendered without the text inside the title tag.

The solution is to create a razor code block near the top of the _Host.cshtml file (just above <!DOCTYPE html>) that looks something like this, so we can render the App component first:

@{
    // This first one will replace the main component that is automatically created by Visual Studio 2019
    var appComponent = await Html.RenderComponentAsync<App>(RenderMode.ServerPrerendered);
    
    // Then add the HeadSection component
    var headComponent = await Html.RenderComponentAsync<HeadSection>(RenderMode.ServerPrerendered);
}

Now, instead of inserting components into the html of _Host.cshtml, insert those variables

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="~/" />
    @headComponent
    <link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
    <link href="css/styles.css" rel="stylesheet" />
</head>

And in the Body

<app>
    @appComponent
</app>

If you right-click on this forum and view the page source, not only will you see the title rendered, but you'll also notice the "sequence" has changed and is showing the App component loaded first (sequence is 0).

Now, in the HeadComponent, you can also add other meta tags to help with your SEO.

You can also see my full _Host.cshtml file in my GitHub repository at: https://github.com/ElliottBrand/BlazorForum/blob/master/BlazorForum/Pages/_Host.cshtml

Someone is typing...

Post a Reply

You must be logged in to add a new post.
Number of online users: 2
An error has occurred. This application may no longer respond until reloaded. Reload 🗙