Skip to content

useScriptTag

类别
导出大小
1.11 kB
最近修改
2 days ago

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

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

如果给定 URL 的 script 标签已经存在,useScriptTag() 不会创建另一个 script 标签,但请注意,取决于你如何使用它,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
()