.NET MAUI Blazor Hybrid app - Razor engine generating <!--!--> comments around JavaScript code

Joachim Petersen 21 Reputation points
2023-08-14T13:45:04.6266667+00:00

I have following razor page for my .NET MAUI Blazor Hybrid app:

@inject IJSRuntime JSRuntime

@code {
	string uniqueIdentifier;
	string componentName;
	string functionName;

	protected override void OnInitialized()
	{
		base.OnInitialized();

		uniqueIdentifier = Guid.NewGuid().ToString("N"); // Generate a unique identifier
		componentName = "rs_" + uniqueIdentifier; // Combine with a prefix
		functionName = "runcode" + uniqueIdentifier; // Combine with a prefix

	}

	protected override async Task OnAfterRenderAsync(bool firstRender)
	{
		if (firstRender)
		{
			await InitializeJsFunction();
		}
	}

	async Task InitializeJsFunction()
	{
		await JSRuntime.InvokeVoidAsync(functionName);
	}
}

<script>
	@functionName = function () {
		$(document).ready(function () {
			"use strict";
			console.log("just some demo JS");
		});
	}
</script>

Razor engine generating <!--!--> comment at the JavaScript code; here is the output from ctrl+shift+i and inspecting the generated element:

<script>runcode4ff28da08715407b8eaacb897b7595f2<!--!--> = function () {
		$(document).ready(function () {
			"use strict";
			console.log("just some demo JS");
		});
	}
</script>

Is this a MAUI/Razor engine bug? (.Net 6) or am I doing something not intended by the razor engine?

Developer technologies | .NET | Blazor
Developer technologies | .NET | .NET MAUI
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 82,686 Reputation points Volunteer Moderator
    2023-08-14T19:47:51.8366667+00:00

    the script tag is not supported in a blazor component anyway. as the html is rendered via a virtual dom, the script tag will not execute. the script should be defined in the initial html file or via js interop.

    note: you should not be using jquery with blazor. as jquery is usually used to update the dom, it can get the blazor razor tree out of sync with the true dom.


Your answer

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