dotnet/skills✦ 精选0°

use-js-interop

仓库创建 2026年2月4日最近提交 14 小时前SkillHot 收录 20 天前
▸ 精选理由

主张 collocated 模块与生命周期管理,避免全局脚本与内存泄露。

这个 Skill 做什么

在 Blazor 中安全调用 JavaScript 并管理 JS/.NET 互操作生命周期。

在 Blazor 里把 JavaScript 调用和 .NET 回调写得稳当:包括用 collocated .razor.js 模块、管理 IJSRuntime / IJSObjectReference /DotNetObjectReference /ElementReference 的生命周期与释放(IAsyncDisposable),并处理服务器端互操作的时序问题。适合组件需要跟 JS 交互或调优互操作稳定性时使用,能避免常见的时序与内存泄露坑。

▸ 展开 SKILL.md 英文原文

Add, review, or fix JavaScript interop in Blazor components. USE FOR: calling JavaScript from Blazor, calling .NET from JavaScript, collocated .razor.js modules, IJSRuntime, IJSObjectReference lifecycle, DotNetObjectReference, ElementReference, timing rules for when JS is available, IAsyncDisposable disposal of JS references, server-side JS interop safety. DO NOT USE FOR: general Blazor component authoring without JS interop needs (use author-component), forms (use collect-user-input).

开发编程JS 互操作IJSRuntime.razor.js通用
4.8k
Stars
351
Forks
40
仓库内 Skill
+610
7 日增星
安装 / 使用
给你的 Agent 一句话(通用)
帮我安装这个 skill:https://raw.githubusercontent.com/dotnet/skills/main/plugins/dotnet-blazor/skills/use-js-interop/SKILL.md
或 curl 直取 SKILL.md
curl -fsSL "https://raw.githubusercontent.com/dotnet/skills/main/plugins/dotnet-blazor/skills/use-js-interop/SKILL.md"
SKILL.MD 节选查看完整文件 ↗
# JS Interop in Blazor

## 1. Collocated JS Modules

Always use collocated `.razor.js` files with `export` — never global `window.*` functions or `<script>` tags.

```javascript
// ChartPanel.razor.js — placed next to ChartPanel.razor
export function initialize(canvas, dotNetRef) { /* ... */ }
export function updateData(points) { /* ... */ }
export function dispose() { /* ... */ }
```

Import paths: same project = `"./Components/ChartPanel.razor.js"`, RCL = `"./_content/{AssemblyName}/..."`.

## 2. Lifecycle Timing

**All JS interop must happen in `OnAfterRenderAsync` or event handlers** — never in `OnInitialized`, `OnParametersSet`, or constructors. JS is not available during server prerend
via SKILL·HOT · 数据来自 GitHub 公开信息 · 原文版权归作者所有