---
title: "useScript()"
description: "useScript 函数的 API 文档。"
canonical_url: "https://nuxt-scripts.zhcndoc.com/docs/api/use-script"
last_updated: "2026-05-22T14:11:55.509Z"
---
试用 StackBlitz 上的 [自定义脚本示例](https://stackblitz.com/github/nuxt/scripts/tree/main/examples/custom-script)。
此组合函数是对 Unhead [useScript](https://unhead.unjs.io/usage/composables/use-script) 的封装,添加了 Nuxt 特有的增强功能,有关完整文档请参考此处。
## 函数签名
```ts
export function useScript = Record>(input: UseScriptInput, options?: NuxtUseScriptOptions): UseScriptContext {}
```
## 参数
### `UseScriptInput`
这是脚本标签的输入。例如,可以传入一个 URL 字符串,或包含脚本标签属性的对象。
```ts
export type UseScriptInput = string | {
src?: string
async?: boolean
defer?: boolean
type?: string
integrity?: string
crossorigin?: string
text?: string
innerHTML?: string
innerText?: string
content?: string
referrerPolicy?: string
attributes?: Record
}
```
更多参数信息请参阅 [脚本输入](https://unhead.unjs.io/usage/composables/use-script#argument-script-options) 文档。
### `NuxtUseScriptOptions`
更多参数信息请参阅 [脚本选项](https://unhead.unjs.io/usage/composables/use-script#argument-use-script-options) 文档。
- `use` - 用于解析脚本的函数。
- `trigger` - [触发脚本加载](/docs/guides/script-triggers)
- `bundle` - 有关更多信息,请参阅 [第一方模式](/docs/guides/first-party)。
```ts
export type NuxtUseScriptOptions = Omit, 'trigger'> & {
/**
* 加载脚本的触发时机:
* - `onNuxtReady` - 当 Nuxt 准备就绪时加载脚本。
* - `manual` - 通过调用 `load()` 手动加载脚本。
* - `Promise` - 当 Promise 解析完成时加载脚本。
*/
trigger?: UseScriptOptions['trigger'] | 'onNuxtReady'
/**
* 是否将脚本打包为资源并从服务器加载。这有利于提升性能,减少额外的 DNS 查询和请求数,
* 同时提升隐私保护,避免将用户 IP 地址泄露给第三方服务器。
* - `true` - 将脚本打包为资源。
* - `false` - 不打包脚本。(默认)
*/
bundle?: boolean | 'force'
/**
* [实验性] 使用 Partytown 在 web worker 中加载脚本。
* 启用后,会为脚本标签添加 `type="text/partytown"`。
* 需要另外安装和配置 @nuxtjs/partytown。
* 注意:需要访问 DOM 的脚本(如 GTM、Hotjar、聊天小部件)不兼容。
* @see https://partytown.qwik.dev/
*/
partytown?: boolean
/**
* 控制此脚本的代理。
* 当为 `false` 时,收集请求直接发送到第三方服务器。
* 当为 `true` 时,收集请求通过 `/_scripts/p/` 代理。
* 默认值取决于注册表中脚本是否具有 `proxy` 能力。
*/
proxy?: boolean
/**
* 跳过脚本输入的任何模式验证。这对于在开发过程中加载脚本存根很有用,
* 无需加载实际脚本且不会收到警告。
*/
skipValidation?: boolean
/**
* 指定预热与第三方脚本连接的策略。
* - `false` - 禁用预加载。
* - `'preload'` - 预加载脚本。
* - `'preconnect'` | `'dns-prefetch'` - 预连接到脚本源。
*/
warmupStrategy?: false | 'preload' | 'preconnect' | 'dns-prefetch'
}
```
## 返回值
更多返回值信息请参阅 [理解代理函数](/docs/guides/key-concepts) 和 [$script](https://unhead.unjs.io/usage/composables/use-script#argument-use-script-options) 文档。
返回对象包含:
- `status` - 响应式 ref,代表脚本状态: `'awaitingLoad'` | `'loading'` | `'loaded'` | `'error'`
- `load()` - 手动加载脚本的函数
- `remove()` - 从 DOM 中移除脚本的函数
- `reload()` - 移除并重新加载脚本的函数(详见下文)
### `reload()`
移除脚本并重新加载,强制重新执行。适用于某些第三方脚本仅在首次加载时扫描 DOM 的场景,需在 SPA 导航后重新运行。
```ts
const { reload } = useScript('https://example.com/dom-scanner.js')
// 导航时重新加载
watch(() => route.path, () => reload())
```
许多第三方脚本自带 SPA 支持(例如 iubenda 的 `_iub.cs.api.activateSnippets()`)。使用 `reload()` 前请先查看脚本文档——它们自带的方法通常更高效。