Skip to content

[Blazor] Framework support for per-page JavaScript logic #52273

@MackinnonBuck

Description

@MackinnonBuck

Overview

One might expect that placing a <script> element in a statically rendered page component should result in the script getting executed each time the page loads. This would be consistent with how other frameworks like Razor Pages and MVC work. However, scripts won't execute if they get dynamically added to the page via enhanced navigation, and this creates inconsistency between full page reloads and enhanced page updates.

We added the blazor.addEventListener("enhancedload", callback) API in .NET 8 so that customers could implement logic that reacts to enhanced page updates. However, this API alone doesn't provide the level of convenience that placing <script> elements directly inside a component does.

Potential solution

Feedback such as #51331 prompted me to create a library to help make it easier to have per-page JavaScript in Blazor Web apps: https://github.com/MackinnonBuck/blazor-page-script.

We should consider bringing a feature like this into the framework. The package's API is a component that takes a path to a JS module, but it would be worthwhile to consider alternative and/or more sophisticated designs. For example, we could allow <script> tags to be placed directly in components, since that's what many customers intuitively try first, and the framework could preprocess them in a special manner so that the code gets executed even with enhanced navigation enabled.

Metadata

Metadata

Assignees

Labels

Pillar: Complete Blazor WebPriority:1Work that is critical for the release, but we could probably ship withoutarea-blazorIncludes: Blazor, Razor ComponentsenhancementThis issue represents an ask for new feature or an enhancement to an existing onefeature-blazor-jsinteropThis issue is related to JSInterop in Blazor

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions