Skip to content
Browser

useScriptTag

Dynamically load and unload an external script tag. The script is appended to document.head on mount and removed on unmount. Supports promise-based control, deduplication of identical scripts, and optional manual lifecycle management.

useScriptTag
Not loaded

Dynamically load and unload an external script tag.

srccdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js
import {
const useScriptTag: (src: MaybeObservable<string>, onLoaded?: (el: HTMLScriptElement) => void, options?: DeepMaybeObservable<UseScriptTagOptions>) => UseScriptTagReturn
useScriptTag
} from "@usels/web";
function
function Component(): JSX.Element
Component
() {
const {
const isLoaded$: ReadonlyObservable<boolean>

True once the script's load event has fired (or a pre-loaded element was found). Resets to false on unload().

isLoaded$
} =
function useScriptTag(src: MaybeObservable<string>, onLoaded?: (el: HTMLScriptElement) => void, options?: DeepMaybeObservable<UseScriptTagOptions>): UseScriptTagReturn

Framework-agnostic dynamic <script> loader. Appends an external script tag to document.head, deduplicates by src, and tracks the load lifecycle.

@paramsrc - Script src (MaybeObservable<string> — read at load time).

@paramonLoaded - Optional callback invoked once the script's load event fires.

@paramoptions - Mount-time-only options (immediate, manual, attrs, etc.).

useScriptTag
("https://cdn.example.com/lib.js", (
el: HTMLScriptElement
el
) => {
any
console
.
any
log
("Script loaded",
el: HTMLScriptElement
el
);
});
return <
JSX.IntrinsicElements.div: DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div
>{
const isLoaded$: ReadonlyObservable<boolean>

True once the script's load event has fired (or a pre-loaded element was found). Resets to false on unload().

isLoaded$
.
ImmutableObservableBase<boolean>.get(trackingType?: TrackingType | GetOptions): {}
get
() ? "Script loaded" : "Loading..."}</
JSX.IntrinsicElements.div: DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div
>;
}

Set manual: true to take full control of when the script loads and unloads.

import { useScriptTag } from "@usels/web";
function Component() {
const { load, unload, isLoaded$ } = useScriptTag(
"https://cdn.example.com/lib.js",
undefined,
{ manual: true }
);
return (
<div>
<button onClick={() => load()}>Load</button>
<button onClick={() => unload()}>Unload</button>
<p>Status: {isLoaded$.get() ? "loaded" : "not loaded"}</p>
</div>
);
}

load() accepts a waitForScriptLoad parameter (default true). When true, the returned promise resolves only after the script’s load event fires. Set to false to resolve immediately after the element is appended.

const { load } = useScriptTag("https://cdn.example.com/lib.js", undefined, { manual: true });
// Resolves after the `load` event fires
await load(true);
// Resolves immediately after appending to DOM
await load(false);
import { useScriptTag } from "@usels/web";
useScriptTag("https://cdn.example.com/lib.js", undefined, {
async: true, // default: true
defer: false,
type: "text/javascript", // default: "text/javascript"
crossOrigin: "anonymous",
referrerPolicy: "no-referrer",
nonce: "abc123",
attrs: { "data-id": "my-lib" },
});
ParameterTypeDescription
srcMaybeObservable<string>- Script src (MaybeObservable<string> — read at load time).
onLoaded(el: HTMLScriptElement) => void (optional)- Optional callback invoked once the script’s load event fires.
optionsUseScriptTagOptions (optional)- Mount-time-only options (immediate, manual, attrs, etc.).
OptionTypeDefaultDescription
immediatebooleantrueLoad the script immediately on mount
asyncbooleantrueSet the script element’s async attribute
typestring"text/javascript"Script MIME type
manualbooleanfalseManual control — if true, load/unload are not called automatically on mount/unmount
crossOrigin"anonymous" | "use-credentials"--
referrerPolicyReferrerPolicy--
noModuleboolean--
deferboolean--
attrsRecord<string, string>-Additional attributes to set on the script element
noncestring--
documentDocument-Custom document instance (useful for iframes or testing)

UseScriptTagReturn

NameTypeDescription
scriptTag$ReadonlyObservable<HTMLScriptElement | null>-
isLoaded$ReadonlyObservable<boolean>True once the script’s load event has fired (or a pre-loaded element was found). Resets to false on unload().
load(waitForScriptLoad?: boolean | undefined) => Promise<boolean | HTMLScriptElement>-
unload() => void-

View on GitHub