This library simplifies the process of loading JavaScript modules and provides methods for waiting until a module is loaded and disposing of modules when they are no longer needed.
- Import JavaScript modules dynamically.
- Wait until a module is fully loaded.
- Dispose of JavaScript modules when they are no longer needed.
- Singleton pattern to ensure that each module is loaded only once.
To install, add the package to your Blazor project using the .NET CLI:
dotnet add package Soenneker.Blazor.Utils.ModuleImport
Register it in DI:
builder.Services.AddModuleImportUtil();
Here's an example of how to use the ModuleImportUtil
in a Blazor component:
@page "/example"
@inject IModuleImportUtil ModuleImportUtil
@implements IAsyncDisposable
<h3>Module Import Example</h3>
<button @onclick="LoadModule">Load Module</button>
@code {
private async Task LoadModule()
{
var module = await ModuleImportUtil.Import("exampleModule");
await ModuleImportUtil.WaitUntilLoaded("exampleModule");
// Guaranteed that the module has been added to the DOM, and available at this point
}
public async ValueTask DisposeAsync()
{
await ModuleImportUtil.DisposeModule("exampleModule");
}
}