useExternal
Loads external JS or CSS and reports the loading status.
Loads external JS or CSS and reports the loading status.
Import
import { useExternal } from '@kamod-ch/hooks'Live demo
Basic demo
Loads external JS or CSS and reports the loading status.
Browser-only demo
This demo starts after the page mounts in the browser.
import { useMemo, useState } from 'preact/hooks'
import { useExternal } from '@kamod-ch/hooks'
export default function UseExternalDemo() {
const [enabled, setEnabled] = useState(false)
const scriptUrl = useMemo(() => {
const blob = new Blob(["window.__kamodHooksExternalLoaded = 'ready'"], { type: 'text/javascript' })
return URL.createObjectURL(blob)
}, [])
const status = useExternal(enabled ? scriptUrl : undefined)
return (
<div>
<p><strong>Status:</strong> {status}</p>
<button type="button" onClick={() => setEnabled(true)}>Load script</button>
</div>
)
}
API
TypeScript signature
type JsOptions = {
type: 'js';
js?: Partial<HTMLScriptElement>;
keepWhenUnused?: boolean;
};
type CssOptions = {
type: 'css';
css?: Partial<HTMLStyleElement>;
keepWhenUnused?: boolean;
};
type DefaultOptions = {
type?: never;
js?: Partial<HTMLScriptElement>;
css?: Partial<HTMLStyleElement>;
keepWhenUnused?: boolean;
};
export type Options = JsOptions | CssOptions | DefaultOptions;
export type Status = 'unset' | 'loading' | 'ready' | 'error';
declare const useExternal: (path?: string, options?: Options) => Status;
export default useExternal;
/SSR considerations
This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.
Browser compatibility
Requires the corresponding browser API to exist in the current environment.