跳到主要内容

useScriptTag

Script 标签注入。

Usage

实时编辑器

// 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: {version}</div>;
};

结果
Loading...

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";