问题
Without using Blazor,
<script>
$(document).ready(function () {
alert('hello')
// what you want to initialize
});
</script>
With Blazor, do I just put the above script in wwwroot/index.html
and call it from Blazor razor page in OnInitializedAsync
method?
回答1:
In Blazor Server App you can add a script tag (in _Host.cshtml file) to your JavaScript file like this:
<script src="_framework/blazor.server.js"></script>
<script src="exampleJsInterop.js"></script>
Your JS file should be placed in the wwwroot folder
And you can call your JavaScript functions from the pair OnAfterRender(Async) as the following code snippet demonstrates:
@inject IJSRuntime JSRuntime
<div @ref="divElement">Text during render</div>
@code {
private ElementReference divElement;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync(
"exampleJsInterop.setElementText", divElement, "Text after render");
}
}
}
Note: Since a Blazor Server app is usually prerendering, JavaScript is not yet available, so you have to wait until your app is rendered, and only then call JavaScript functions. Note also that the code above check if this is the first time the app is rendered...this is the place where you should initialize your JavaScript object.
Note: The above is not applicable to WebAssembly Apps, as JavaScript is available from the very beginning.
In WebAssembly Apps you should place the tag that references your JavaScript file in the wwwroot/index.html, like the following:
<script src="_framework/blazor.webassembly.js"></script>
<script src="exampleJsInterop.js"></script>
Note that you still need to call your JavaScript functions from the OnAfterRender(Async) pair.
I hope that helps! If you get stuck, let me know
来源:https://stackoverflow.com/questions/62859002/how-do-i-make-a-javascript-function-available-after-the-document-is-loaded-in-bl