Skip to main content

useScriptTag

Script tag injecting

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
Loading...

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'