【发布时间】:2021-02-21 13:11:12
【问题描述】:
在 Blazor 中有几个用于执行 JavaScript 代码的选项:
- 将 js 文件加载到 IJSObjectReference 的实例中并在其上调用 InvokeAsync:
Blazor 组件的代码隐藏文件:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
IJSObjectReference module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", ".script1.js");
await module.InvokeVoidAsync("sampleFunction1");
}
}
- 将 js 文件作为脚本添加到 HTML 标记并在 IJSRuntime 实例上调用 InvokeAsync:
index.html:
<script src="script1.js"></script>
Blazor 组件的代码隐藏文件:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("sampleFunction1");
}
}
这两种方法都有效,但从性能、代码维护和代码清洁度的角度来看,哪一种更受欢迎?
【问题讨论】:
标签: blazor blazor-client-side blazor-webassembly asp.net-blazor