dotnet / dotnet/aspnetcore

[Blazor] Framework support for per-page JavaScript logic

Open
#52,273 18 comments 31 reactions 1 assignee Claimed by @javiercn View on GitHub
area-blazor enhancement feature-blazor-jsinterop on-roadmap Pillar: Complete Blazor Web Priority:1
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

## Overview
One might expect that placing a `` 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 https://github.com/dotnet/aspnetcore/issues/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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.