useScriptTag

Script 标签注入。

useScriptTag 动态注入 <script> 标签到文档中并管理其生命周期。它返回一个包含脚本元素、加载状态("idle""loading""ready""error")、load 函数和 unload 函数的元组。该 hook 支持 asyncdefertypecrossOriginreferrerPolicy、自定义属性和手动加载/卸载控制等选项。

使用场景

  • 按需加载第三方库(分析、小部件、地图),而非在构建时加载
  • 延迟加载重量级脚本直到组件挂载或用户交互发生
  • 根据运行时条件动态加载不同的脚本版本或配置

注意事项

  • SSR 安全:该 hook 在服务端渲染期间为空操作。服务端不会创建 <script> 元素。状态将保持 "idle" 直到组件在浏览器中挂载。
  • 生命周期管理:组件卸载时脚本会自动从 DOM 中移除(除非设置了 manualtrue)。使用 loadunload 进行精细控制。
  • 去重:如果文档中已存在具有相同 src 的脚本,hook 将复用它而不是创建副本。

Usage

Live Editor

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

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}</div>;
};
Result

API

useScriptTag

Returns

readonly [HTMLScriptElement | null, UseScriptTagStatus, (waitForScriptLoad?: boolean | undefined) => Promise<boolean | HTMLScriptElement>, () => void]: 包含以下元素的元组:

  • 用来加载资源的 html 元素。
  • 资源加载状态。
  • 资源加载函数。
  • 资源卸载函数

Arguments

参数名描述类型默认值
src资源地址string (必填)-
onLoaded资源加载完成的回调((el: HTMLScriptElement) => void) | undefined-
options可选参数UseScriptTagOptions | undefined-

UseScriptTagOptions

参数名描述类型默认值
immediate立即加载资源booleantrue
asyncscript 标签上加上 asyncbooleantrue
type脚本类型string'text/javascript'
manual手动控制加载和卸载时机booleanfalse
crossOrigin跨域属性'anonymous' | 'use-credentials'-
referrerPolicy来源属性| 'no-referrer'| 'no-referrer-when-downgrade'| 'origin'| 'origin-when-cross-origin'| 'same-origin'| 'strict-origin'| 'strict-origin-when-cross-origin'| 'unsafe-url'-
noModulescript 标签上加上 noModuleboolean-
deferscript 标签上加上 deferboolean-
attrs在 script 标签上添加自定义属性Record<string, string>-

UseScriptTagStatus

Type

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