Skip to content

useScriptTag

类别
导出体积
1.16 kB
上次更改
3 months ago

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

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

用法

ts
import { 
useScriptTag
} from '@vueuse/core'
useScriptTag
(
'https://player.twitch.tv/js/embed/v1.js', // 当脚本标签加载完成时的回调。 (
el
: HTMLScriptElement) => {
// 做一些事情 }, )
js
import { useScriptTag } from '@vueuse/core'
useScriptTag(
  'https://player.twitch.tv/js/embed/v1.js',
  // 当脚本标签加载完成时的回调。
  (el) => {
    // 做一些事情
  },
)

该脚本将在组件挂载时自动加载,并在组件卸载时删除。

配置

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

ts
import { 
useScriptTag
} from '@vueuse/core'
const {
scriptTag
,
load
,
unload
} =
useScriptTag
(
'https://player.twitch.tv/js/embed/v1.js', () => { // 做一些事情 }, {
manual
: true },
) // 手动控制 await
load
()
await
unload
()

类型声明

显示类型声明
ts
export interface UseScriptTagOptions extends ConfigurableDocument {
  /**
   * 立即加载脚本
   *
   * @default true
   */
  
immediate
?: boolean
/** * 在脚本标签中添加 `async` 属性 * * @default true */
async
?: boolean
/** * 脚本类型 * * @default 'text/javascript' */
type
?: string
/** * 手动控制加载和卸载的时机 * * @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
/** * 在脚本标签中添加自定义属性 * */
attrs
?:
Record
<string, string>
/** * Nonce value for CSP (Content Security Policy) * @default undefined */
nonce
?: string
} /** * 异步加载脚本标签。 * * @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
:
ShallowRef
<HTMLScriptElement | null, HTMLScriptElement | null>
load
: (
waitForScriptLoad
?: boolean) =>
Promise
<HTMLScriptElement | boolean>
unload
: () => void
} export type
UseScriptTagReturn
=
ReturnType
<typeof
useScriptTag
>

源码

源码文档

贡献者

Anthony Fu
一纸忘忧
Anthony Fu
IlyaL
Denis Blazhkun
BeamDong
Robin
Fernando Fernández
Robin
Craig Riley
David B Ludlow
Levi (Nguyễn Lương Huy)
Tomáš Livora
webfansplz
Preston Alvarado
Shinigami
Alex Kozack
Yaël GUILLOUX

更新日志

57370 - fix: support passing nonce (#4753)
7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
c6c6e - feat: use useEventListener where it was not being used (#4479)
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)