fn
useScriptTag
v0.0.14testeddemoDynamically inject and manage a <script> tag. The returned
load/unload controls append the element to the document <head> (reusing
an existing tag with the same src) and resolve once the script has loaded.
Loading is de-duplicated, listeners are passive, and everything is SSR-safe.
Examples
ts
const { scriptTag, load, unload } = useScriptTag(
'https://example.com/sdk.js',
(el) => console.log('loaded', el),
);ts
// Manual control
const { load, unload } = useScriptTag('https://example.com/a.js', undefined, { manual: true });
await load();
unload();Demo
Loading demo…
Signature
ts
export function useScriptTag(
src: MaybeRefOrGetter<string>,
onLoaded: (el: HTMLScriptElement) => void = noop,
options: UseScriptTagOptions ={ ... }Parameters
| Parameter | Type | Description |
|---|---|---|
src | MaybeRefOrGetter<string> | Reactive source URL for the script |
onLoaded? | (el: HTMLScriptElement) => void | Called when the script finishes loading |
options? | UseScriptTagOptions | Options |
Returns
UseScriptTagReturn{ scriptTag, load, unload }| Property | Type | Description |
|---|---|---|
scriptTag | ShallowRef<HTMLScriptElement | null> | Reactive reference to the underlying <script> element, or null when not loaded. |
load | (waitForScriptLoad?: boolean) => Promise<HTMLScriptElement | boolean> | Load the script into the document <head>. |
unload | () => void | Remove the <script> element from the document <head>. |