コンテンツへスキップ

useScriptTag

カテゴリ
エクスポートサイズ
676 B
最終更新日
先週

アンマウント時にスクリプトタグを自動的にアンロード(削除)する機能を備えたスクリプトタグを作成します。

指定されたURLのスクリプトタグが既に存在する場合、useScriptTag()は別のスクリプトタグを作成しませんが、使用方法によっては、useScriptTag()が既にその特定のJSファイルを前のuseScriptTag()の呼び出しでロードしてアンロードしている可能性があることに注意してください。

使用方法

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
  },
)

スクリプトは、コンポーネントがマウントされたときに自動的にロードされ、コンポーネントがアンマウントされたときに削除されます。

設定

スクリプトのロードタイミングを手動で制御するには、manual: trueを設定します。

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.dokyumento.jp/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>

ソース

ソースドキュメント

コントリビューター

Anthony Fu
Denis Blazhkun
Anthony Fu
Craig Riley
David B Ludlow
Levi (Nguyễn Lương Huy)
Tomáš Livora
webfansplz
Preston Alvarado
Shinigami
Alex Kozack
Yaël GUILLOUX

変更ログ

v12.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2サポートの削除、バンドルの最適化、クリーンアップ (#4349)
v10.0.0-beta.4 2023/4/13
4d757 - feat(types)!: MaybeComputedRefの名前をMaybeRefOrGetterに変更
0a72b - feat(toValue): resolveUnrefの名前をtoValueに変更

MITライセンスに基づき公開されています。