The ResourceLoader
class is designed to manage the loading and initialization of scripts, styles, and JavaScript modules in a Blazor application. It provides methods to asynchronously load scripts and styles, wait for variables to be available, and manage the lifecycle of JavaScript modules.
It ensures that each resource is only loaded once (through this interop), even with multiple concurrent calls.
dotnet add package Soenneker.Blazor.Utils.ResourceLoader
To load a script, use the LoadScript
method. It injects the file into the DOM.
await resourceLoader.LoadScript("https://example.com/script.js");
LoadScriptAndWaitForVariable
is also available. It waits for a specified JavaScript variable to be available:
await resourceLoader.LoadScriptAndWaitForVariable("https://example.com/script.js", "variableName");
To load a style, use the LoadStyle
method. It injects the file into the DOM.
await resourceLoader.LoadStyle("https://example.com/style.css");
To import a JavaScript module, use the ImportModule
method:
var module = await resourceLoader.ImportModule("moduleName");
You probably want ImportModuleAndWaitUntilAvailable
, as that waits until the module is loaded, and accessible:
// 'ResourceLoader' is the name of the export class
var module = await resourceLoader.ImportModuleAndWaitUntilAvailable("Soenneker.Blazor.Utils.ResourceLoader/resourceloader.js", "ResourceLoader");
To wait for a JavaScript variable to be available, use the WaitForVariable
method:
await resourceLoader.WaitForVariable("variableName");
Be sure to dispose of a module after you're done interacting with it. To dispose of a JavaScript module, use the DisposeModule
method:
await resourceLoader.DisposeModule("moduleName");