How can I write a script in the head of some of my Blazor pages?

David Thielen 3,121 Reputation points
2024-08-20T15:33:49.7333333+00:00

Hi all;

I want to write event structured data in the <head> of some of my Blazor pages, where the content is specific to the page.

So it is:

<head>
    <script type="application/ld+json">
        /* 15 - 30 lines of JSON */
    </script>
</head>

This would get added to App.razor I think.

Do I put a string [CascadingParameter] in App.razor.cs, set it as @MyEventScript in App.razor, and then assign it in the child @Body MyPage.razor.cs?

I'm asking for what is a supported way to do this. (Not the opinion "best", but what approach is using supported functionality in Blazor and therefore will continue to work in future versions.)

thanks - dave

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,584 questions
0 comments No comments
{count} votes

Accepted answer
  1. Brando Zhang-MSFT 3,696 Reputation points Microsoft Vendor
    2024-08-21T02:21:56.47+00:00

    Hi @,

    I suggest you could directly using the HeadContent component to set the header inside each razor page, like below:

    By using this , there is no need to use any CascadingParameter inside the blazor.

    @page "/"
    <PageTitle>Home</PageTitle>
    <h1>Hello, world!</h1>
    Welcome to your new app.
    <HeadContent>
        <script type="application/ld+json">
         @PageHeadContent
        </script>
    </HeadContent>
    @code{
        public string? PageHeadContent { get; set; }
        //here you could set the content from the database
        protected override void OnInitialized()
        {
            PageHeadContent="test";
        }
    }
     
    
    

    Result:

    User's image*****************************************************

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

     

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 65,576 Reputation points
    2024-08-21T15:57:40.47+00:00

    remember a web crawler will only have access to the pre-render html produced by blazor (no OnInitializedAsync() or events) . you can test your site's static content by disabling javascript in the browser then accessing the blazor server site.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.