useScriptTag

Script tag injecting

useScriptTag dynamically injects a <script> tag into the document and manages its lifecycle. It returns a tuple of the script element, a loading status ("idle", "loading", "ready", or "error"), a load function, and an unload function. The hook supports options for async, defer, type, crossOrigin, referrerPolicy, custom attributes, and manual load/unload control.

When to Use

  • Loading third-party libraries (analytics, widgets, maps) on demand rather than at build time
  • Deferring heavy scripts until a component mounts or a user interaction occurs
  • Dynamically loading different script versions or configurations based on runtime conditions

Notes

  • SSR-safe: The hook is a no-op during server-side rendering. No <script> elements are created on the server. The status will be "idle" until the component mounts in the browser.
  • Lifecycle management: The script is automatically removed from the DOM when the component unmounts (unless manual is set to true). Use load and unload for fine-grained control.
  • Deduplication: If a script with the same src already exists in the document, the hook will reuse it rather than creating a duplicate.

Usage

Live Editor
// it's an example, use your types instead

// Add this if you are using TypeScript
// declare const jQuery: any;
function Demo() {
  const [, status] = useScriptTag(
    "https://code.jquery.com/jquery-3.5.1.min.js",
  );

  const [version, setVersion] = useState(0);
  useEffect(() => {
    if (typeof jQuery !== "undefined") {
      setVersion(jQuery.fn.jquery);
    }
  }, [status]);

  return <div>jQuery version: {version}</div>;
};
Result

API

useScriptTag

Returns

readonly [HTMLScriptElement | null, UseScriptTagStatus, (waitForScriptLoad?: boolean | undefined) => Promise<boolean | HTMLScriptElement>, () => void]: A tuple with the following elements:

  • html element used to load resources.
  • Resource loading status.
  • Resource loading function.
  • Resource unloading function

Arguments

ArgumentDescriptionTypeDefaultValue
srcsourcestring (Required)-
onLoadedsource loaded callback((el: HTMLScriptElement) => void) | undefined-
optionsoptional paramsUseScriptTagOptions | undefined-

UseScriptTagOptions

PropertyDescriptionTypeDefaultValue
immediateLoad the script immediatelybooleantrue
asyncAdd async attribute to the script tagbooleantrue
typeScript typestring'text/javascript'
manualManual controls the timing of loading and unloadingbooleanfalse
crossOrigincross origin'anonymous' | 'use-credentials'-
referrerPolicyreferrer policy| 'no-referrer'| 'no-referrer-when-downgrade'| 'origin'| 'origin-when-cross-origin'| 'same-origin'| 'strict-origin'| 'strict-origin-when-cross-origin'| 'unsafe-url'-
noModuleAdd noModule attribute to the script tagboolean-
deferAdd defer attribute to the script tagboolean-
attrsAdd custom attribute to the script tagRecord<string, string>-

UseScriptTagStatus

Type

export type UseScriptTagStatus = 'idle' | 'loading' | 'ready' | 'error'