Skip to content

useScript

Hook to dinamically load an external script like Google Analitycs.

Demo

INFO

The component load jQuery script by useScript hook and when it is ready displays the jQuery version. When the component unmount, the script is removed. The script is loaded by appendScript function inside a timeout to allow visibility status changes.

Loading demo…
Show source code
tsx
import { useEffect } from "react";
import { useScript } from "../../../../hooks/api-dom/useScript"
declare const jQuery: { fn: { jquery: string } };

export const UseScript = () => {
	const [status, append, remove] = useScript(
		{
			src: `https://code.jquery.com/jquery-3.5.1.min.js`
		},
		{
			handleAppending: true,
		}
	)
	const message: string = status === "ready" ? jQuery.fn.jquery : "N.D.";

	useEffect(() => {
		const id = setTimeout(() => {
			append();
		}, 3000);
		return () => {
			clearTimeout(id);
			remove();
		};
	}, [append, remove]);
	return (<>
		<p>Script status: {status}</p>
		<p>jQuery version: {message}</p>
	</>);
}

Types

UseScriptProps

Props for the useScript.

PropertyTypeRequiredDescription
attributes{ src?: string; async?: boolean; crossorigin?: "anonymous" \| "use-credentials" \| ""; defer?: boolean; fetchpriority?: "high" \| "low" \| "auto"; integrity?: string; nomodule?: boolean; nonce?: string; referrerpolicy?: \| "no-referrer" \| "no-referrer-when-downgrade" \| "origin" \| "origin-when-cross-origin" \| "same-origin" \| "strict-origin" \| "strict-origin-when-cross-origin" \| "unsafe-url"; type?: string; }HTML &lt;script&gt; element attributes to set on the injected script tag.
options{ handleAppending?: boolean; removeOnUnmount?: boolean; iframe?: HTMLIFrameElement; }Behavioural options for the hook itself.

UseScriptStatus

Loading status of the script, returned as the first element of useScript's result tuple.

ts
export type UseScriptStatus = "idle" | "loading" | "error" | "ready";

UseScript

Function signature for the useScript.

InputInput DescriptionReturnReturn Description
(attributes: UseScriptProps["attributes"], options: UseScriptProps["options"]): [ statusFunction signature for the useScript.UseScriptStatus, (attributes?: UseScriptProps["attributes"], iframe?: HTMLIFrameElement) => void, () => void ];

Released under the MIT License.