unloadResource()
unloadResource() removes a previously loaded resource from the DOM and clears its internal state, allowing it to be loaded again with include().
Signature
Section titled “Signature”ResourceLoader.unloadResource(url: string): voidParameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
url | string | The URL of the resource to unload |
Behavior
Section titled “Behavior”Calling unloadResource(url):
- Removes all
<script src="url">and<link href="url">elements from the DOM (both<head>and<body>) - Deletes the cached Promise for that URL
- Sets the resource state to
'unloaded'
For JSON and blob resources (which are not DOM elements), it clears the internal state but does not revoke any object URLs — that is the caller’s responsibility.
Examples
Section titled “Examples”Basic Unload
Section titled “Basic Unload”// Load a stylesheetawait ResourceLoader.include(['https://cdn.example.com/theme.css']);console.log(ResourceLoader.getResourceState('https://cdn.example.com/theme.css'));// → 'loaded'
// Unload itResourceLoader.unloadResource('https://cdn.example.com/theme.css');console.log(ResourceLoader.getResourceState('https://cdn.example.com/theme.css'));// → 'unloaded'Hot-Swapping a Stylesheet
Section titled “Hot-Swapping a Stylesheet”A common use case is swapping between themes:
let currentTheme = null;
async function switchTheme(themeName) { // Unload the current theme if (currentTheme) { ResourceLoader.unloadResource(currentTheme); }
// Load the new theme const newThemeUrl = `https://cdn.example.com/themes/${themeName}.css`; await ResourceLoader.include([newThemeUrl]); currentTheme = newThemeUrl; console.log(`Switched to theme: ${themeName}`);}
// Usageawait switchTheme('dark');await switchTheme('light');Plugin System
Section titled “Plugin System”const loadedPlugins = new Map();
async function loadPlugin(name, url) { if (loadedPlugins.has(name)) { console.log(`Plugin ${name} already loaded.`); return; } await ResourceLoader.include([url]); loadedPlugins.set(name, url);}
function unloadPlugin(name) { const url = loadedPlugins.get(name); if (url) { ResourceLoader.unloadResource(url); loadedPlugins.delete(name); console.log(`Plugin ${name} unloaded.`); }}
// Usageawait loadPlugin('charts', 'https://cdn.example.com/charts.js');unloadPlugin('charts');- Calling
unloadResource()on a URL that was never loaded (or was already unloaded) is a no-op. - After calling
unloadResource(), a subsequentinclude()with the same URL will load the resource fresh from the network. - For blob resources, object URLs created by
URL.createObjectURL()are not revoked automatically. CallURL.revokeObjectURL(objectUrl)manually to free memory.