Blazor is a new single-page web application development framework from Microsoft. Blazor allows .Net developers to quickly develop single-page applications because it uses C sharp instead of JavaScript to write the client-side logic.
A challenge that I faced recently while developing a Blazer application was to dynamically add a JavaScript file that was used only in a single component. Blazer allows adding script tags only to the root HTML document. This makes it difficult to add JavaScript files that are required only in a single or few components.
In this post, I'll explain how we can add JavaScript code dynamically to a single component in Blazor.
Add Script To Components
To load a script file in a component, we should first, add a JavaScript function that loads the JavaScript from the specified URL to the main JavaScript file of the project.
The source code of this project can be downloaded from GitHub.
Create a script loader
Add a new function to the script.js file. This function will load a script file from the specified URL.
function loadJs(sourceUrl) {
if (sourceUrl.Length == 0) {
console.error("Invalid source URL");
return;
}
var tag = document.createElement('script');
tag.src = sourceUrl;
tag.type = "text/javascript";
tag.onload = function () {
console.log("Script loaded successfully");
}
tag.onerror = function () {
console.error("Failed to load script");
}
document.body.appendChild(tag);
}
Add this script file to the root document _Host.cshtml. This file will be located in the Shared folder.
/* Add this code above the Blazor server script */
<script src="/js/site.js"></script>
<script src="_framework/blazor.server.js"></script>
Inject IJSRuntime
Go to the Index.razor component, or any other component where you want to load scripts dynamically inject the IJSRuntime.
@inject IJSRuntime _js
Then, override the OnAfterRenderAsync method and call the loadJs function.
protected override async Task OnAfterRenderAsync(bool firstRender)
{
var targetUrl = "https://unpkg.com/sweetalert/dist/sweetalert.min.js";
await _js.InvokeVoidAsync("loadJs", targetUrl);
}
In this example, we are loading the Sweetalert library from a CDN. You can replace this URL with the URL to your JavaScript code.
Invoke JS Using IJSRuntime
Now, we have loaded a new script file dynamically from the component. Any function from the newly added script can be called with the help of IJSRuntime.
Here's an example.
@page "/"
@inject IJSRuntime _js;
<h1>Hello, world!</h1>
Welcome to your new app.
<button @onclick="Alert">Show Alert</button>
@code{
protected override async Task OnAfterRenderAsync(bool firstRender)
{
var targetUrl = "https://unpkg.com/sweetalert/dist/sweetalert.min.js";
await _js.InvokeVoidAsync("loadJs", targetUrl);
}
async Task Alert()
{
await _js.InvokeVoidAsync("swal", "Success!", "Script loaded", "success");
}
}
I hope this post will help you. Happy coding. If you have any questions, let me know in the comments below.