Skip to content

A Blazor JavaScript module for dynamically loading scripts and styles

License

Notifications You must be signed in to change notification settings

soenneker/soenneker.blazor.utils.resourceloader

Repository files navigation

Soenneker.Blazor.Utils.ResourceLoader

A Blazor JavaScript interop for dynamically loading scripts, styles, and modules

Overview

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.

Table of Contents

Installation

dotnet add package Soenneker.Blazor.Utils.ResourceLoader

Usage

Loading Scripts

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");

Loading Styles

To load a style, use the LoadStyle method. It injects the file into the DOM.

await resourceLoader.LoadStyle("https://example.com/style.css");

Importing Modules

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");

Waiting for Variables

To wait for a JavaScript variable to be available, use the WaitForVariable method:

await resourceLoader.WaitForVariable("variableName");

Disposing Modules

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");