useScriptTag
A React Hook that helps to apply a script tag to the document with ease in React.
Demo
Usage
See API for more details.
Source
Click links below to view source on GitHub.
API
const { scriptTag, load, unload } = useScriptTag(src, onLoaded, options)
Src
A string
that represents the URL of the script to be loaded.
OnLoaded
A function
that will be called when the script is loaded.
Options
export type ReferrerPolicy =
| 'no-referrer'
| 'no-referrer-when-downgrade'
| 'origin'
| 'origin-when-cross-origin'
| 'same-origin'
| 'strict-origin'
| 'strict-origin-when-cross-origin'
| 'unsafe-url'
export interface UseScriptTagOptions {
/**
* Whether load script immediately at mount
*
* @defaultValue true
*/
immediate?: boolean
/**
* Whether the script is loaded asynchronously
*
* @defaultValue true
*/
async?: boolean
/**
* The type of the script
*
* @defaultValue 'text/javascript'
*/
type?: string
/**
* Whether to control the loading of the script manually
*
* @defaultValue false
*/
manual?: boolean
/**
* The value of the `crossorigin` attribute
*
* @defaultValue undefined
*/
crossOrigin?: 'anonymous' | 'use-credentials'
/**
* The value of the `referrerpolicy` attribute
*
* @defaultValue undefined
*/
referrerPolicy?: ReferrerPolicy
/**
* Whether the script is a module script
*
* @defaultValue undefined
*/
noModule?: boolean
/**
* Whether the script is deferred
*
* @defaultValue false
*/
defer?: boolean
/**
* Additional attributes to be set on the script element
*
* @defaultValue {}
*/
attrs?: Record<string, string>
}
Returns
export type UseScriptTagReturns = {
/**
* The script element Ref
*/
scriptTag: MutableRefObject<HTMLScriptElement | null>
/**
* Load the script
*
* @param waitForScriptLoad Whether to wait for the script to be loaded, `true` by default
*/
load: (waitForScriptLoad?: boolean) => Promise<HTMLScriptElement | boolean>
/**
* Unload the script
*/
unload(): void
}