Skip to content

useScriptTag

创建脚本标签,支持在卸载时自动卸载(删除)脚本标签。

¥Creates a script tag, with support for automatically unloading (deleting) the script tag on unmount.

如果给定 URL 已存在脚本标记,useScriptTag() 将不会创建另一个脚本标记,但请记住,根据你的使用方式,useScriptTag() 可能已经从之前的 useScriptTag() 调用中加载然后卸载了该特定 JS 文件。

¥If a script tag already exists for the given URL, useScriptTag() will not create another script tag, but keep in mind that depending on how you use it, useScriptTag() might have already loaded then unloaded that particular JS file from a previous call of useScriptTag().

用法

¥Usage

ts
import { useScriptTag } from '@vueuse/core'

useScriptTag(
  'https://player.twitch.tv/js/embed/v1.js',
  // on script tag loaded.
  (el: HTMLScriptElement) => {
    // do something
  },
)
js
import { useScriptTag } from '@vueuse/core'
useScriptTag(
  'https://player.twitch.tv/js/embed/v1.js',
  // on script tag loaded.
  (el) => {
    // do something
  },
)

该脚本会在组件安装时自动加载,在组件卸载时自动删除。

¥The script will be automatically loaded when the component is mounted and removed when the component is unmounted.

配置

¥Configuration

设置 manual: true 以手动控制加载脚本的时间。

¥Set manual: true to have manual control over the timing to load the script.

ts
import { useScriptTag } from '@vueuse/core'

const { scriptTag, load, unload } = useScriptTag(
  'https://player.twitch.tv/js/embed/v1.js',
  () => {
    // do something
  },
  { manual: true },
)

// manual controls
await load()
await unload()

类型声明

显示类型声明
typescript
export interface UseScriptTagOptions extends ConfigurableDocument {
  /**
   * Load the script immediately
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Add `async` attribute to the script tag
   *
   * @default true
   */
  async?: boolean
  /**
   * Script type
   *
   * @default 'text/javascript'
   */
  type?: string
  /**
   * Manual controls the timing of loading and unloading
   *
   * @default false
   */
  manual?: boolean
  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"
  noModule?: boolean
  defer?: boolean
  /**
   * Add custom attribute to the script tag
   *
   */
  attrs?: Record<string, string>
}
/**
 * Async script tag loading.
 *
 * @see https://vueuse.org/useScriptTag
 * @param src
 * @param onLoaded
 * @param options
 */
export declare function useScriptTag(
  src: MaybeRefOrGetter<string>,
  onLoaded?: (el: HTMLScriptElement) => void,
  options?: UseScriptTagOptions,
): {
  scriptTag: Ref<HTMLScriptElement | null, HTMLScriptElement | null>
  load: (waitForScriptLoad?: boolean) => Promise<HTMLScriptElement | boolean>
  unload: () => void
}
export type UseScriptTagReturn = ReturnType<typeof useScriptTag>

源代码

源代码文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号