Skip to content

useScriptTag

Category
Export Size
789 B
Last Changed
5 days ago

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

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
edf6f - fix(core): resolve useScriptTag audit findings (#635)

Released under the MIT License. v0.1.8