
If you're wiring up JavaScript in a Blazor app and keep tripping over timing bugs or leaked module references, this one covers the parts that usually go wrong. It focuses on collocated .razor.js modules, initializing JS only in OnAfterRenderAsync so server prerendering doesn't break, merging consecutive .NET-to-JS calls into one round-trip, and wrapping IJSObjectReference lifecycle in a small IAsyncDisposable class. It also covers DotNetObjectReference callbacks, including the easy-to-miss rule that JSInvokable methods must be public. The batching advice is the part I'd pay closest attention to, since chatty interop is a common performance drag in Blazor Server. It's clearly scoped to JS interop, so pair it with author-component for general component work.
$ npx -y skills add dotnet/skills --skill use-js-interop --agent claude-codeInstalls into .claude/skills of the current project.
Always use collocated .razor.js files with export — never global window.* functions or <script> tags.
// 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}/...".
All JS interop must happen in OnAfterRenderAsync or event handlers — never in OnInitialized, OnParametersSet, or constructors. JS is not available during server prerendering.
Use a typed interop wrapper (see Section 4) — never call InvokeAsync/InvokeVoidAsync with raw string literals:
private ChartInterop? _chart;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
_chart = new ChartInterop(JS);
await _chart.InitializeAsync(_canvasRef);
}
}
Parameter changes: set a flag in OnParametersSet, apply in OnAfterRenderAsync:
private bool _dataChanged;
Sponsors