Skip to content

Assess guidance on use of <script> tags in components #34371

@guardrex

Description

@guardrex

Description

Language from the article section ...

Only place a `<script>` tag in a component file (`.razor`) if the component is guaranteed to adopt [static server-side rendering (static SSR)](xref:blazor/fundamentals/index#client-and-server-rendering-concepts) because the `<script>` tag can't be updated dynamically. Placing a `<script>` tag in a component file doesn't produce a compile-time warning or error, but script loading behavior might not match your expectations in components that adopt an interactive render mode.

The current guidance was provided by the PU in the 8.0 era with additional updates perhaps twice since then, but per @hakenr ...

... it’s not the difference between interactive and static rendering that makes the difference.

It’s due to the page lifecycle and the nature of navigation in such scenarios.

Even with static SSR, when enhanced navigation is enabled, the behavior of dynamically added, removed, or modified scripts gets tricky:

  • The onLoad event doesn’t work as expected.
  • Blazor events like webStart and enhanceNavigation need to be used instead.

I think it’s only safe to use the <script> tag in the statically rendered root component (App.razor), where the script tag itself isn’t expected to change, appear, or disappear. 😇

We'll try to get a PU engineer, probably Javier, on in January to help improve the section. The important bit on the compile-time error going away is true. Javier did remove that at 8.0 on dotnet/razor#8744. The summary from his PR that supports the current language is (emphasis added) ...

  • Removes the check that we have to produce an error when you include a script tag inside a Razor file.
  • We used to have this check to preclude people accidentally adding script tags to their components, since in the context of interactive rendering it does not do what they expect.
  • As we are rendering components statically in .NET 8.0, this warning/errors creates more problems than it solves, and there is no reason for us to keep it around, and instead, we will let the customers do as they see fit.

Page URL

https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/location-of-javascript?view=aspnetcore-9.0

Content source URL

https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/blazor/javascript-interoperability/location-of-javascript.md

Document ID

af240267-89c0-f192-7807-cf426001ad8d

Article author

@guardrex

Related Issues

Metadata

Metadata

Assignees

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions