Appearance
useScriptTag
Creates a script tag
If a script tag already exists for the given URL, useScriptTag() will not create another script tag, but keep in mind that depending on how you use it, useScriptTag() might have already loaded then unloaded that particular JS file from a previous call of useScriptTag().
Demo
Usage
tsx
import { useScriptTag } from '@reause/core'
const { scriptTag, load, unload } = useScriptTag(
'https://player.twitch.tv/js/embed/v1.js',
// on script tag loaded.
(el: HTMLScriptElement) => {
// do something
},
)The script will be automatically loaded when the component is mounted and removed when the component is unmounted.
Configuration
Set manual: true to have manual control over the timing to load the script:
tsx
const { scriptTag, load, unload } = useScriptTag(
'https://player.twitch.tv/js/embed/v1.js',
() => {
// do something
},
{ manual: true },
)
// manual controls
await load()
await unload()Type Declarations
ts
export interface UseScriptTagOptions {
immediate?: boolean;
manual?: boolean;
async?: boolean;
type?: string;
crossOrigin?: 'anonymous' | 'use-credentials';
referrerPolicy?: 'no-referrer' | 'no-referrer-when-downgrade' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url';
noModule?: boolean;
defer?: boolean;
attrs?: Record<string, string>;
nonce?: string;
document?: Document;
}
export interface UseScriptTagReturn {
scriptTag: HTMLScriptElement | null;
load: (waitForScriptLoad?: boolean) => Promise<HTMLScriptElement | boolean>;
unload: () => void;
}
export function useScriptTag(src: string, onLoaded?: (el: HTMLScriptElement) => void, options?: UseScriptTagOptions): UseScriptTagReturn