如何在NuxtJs配置文件中将含自执行函数的script添加到head标签
Nuxt.js 注入自执行Script到Head标签的实现方案
根据你使用的Nuxt版本选择对应操作即可:
Nuxt 2.x 版本
全局注入(所有页面生效)
修改项目根目录的nuxt.config.js,新增如下配置:
export default { head: { script: [ { innerHTML: `(function (c, p, d, u, id, i) { id = ''; // 可选:填入你系统内的用户自定义ID u = 'https://example.com/attribution_tracking/conversions/' + c + '.js?p=' + encodeURI(p) + '&e=' + id; i = document.createElement('script'); i.type = 'application/javascript'; i.async = true; i.src = u; d.getElementsByTagName('head')[0].appendChild(i); }("6666", document.location.href, document));`, type: 'text/javascript', charset: 'utf-8' } ], // 必须添加该配置,防止Nuxt自动转义脚本内的特殊字符 __dangerouslyDisableSanitizers: ['script'] } }
单页面注入(仅当前页面生效)
在对应页面的.vue文件内添加head配置即可:
export default { head() { return { script: [ // 同上的script配置内容 ], __dangerouslyDisableSanitizers: ['script'] } } }
Nuxt 3.x 版本
全局注入(所有页面生效)
修改项目根目录的nuxt.config.ts,新增如下配置:
export default defineNuxtConfig({ app: { head: { script: [ { innerHTML: `(function (c, p, d, u, id, i) { id = ''; // 可选:填入你系统内的用户自定义ID u = 'https://example.com/attribution_tracking/conversions/' + c + '.js?p=' + encodeURI(p) + '&e=' + id; i = document.createElement('script'); i.type = 'application/javascript'; i.async = true; i.src = u; d.getElementsByTagName('head')[0].appendChild(i); }("6666", document.location.href, document));`, type: 'text/javascript' } ] } } })
单页面/组件注入(仅当前范围生效)
在对应页面/组件的<script setup>内直接调用useHead:
<script setup> useHead({ script: [ { innerHTML: `(function (c, p, d, u, id, i) { id = ''; // 可选:填入你系统内的用户自定义ID u = 'https://example.com/attribution_tracking/conversions/' + c + '.js?p=' + encodeURI(p) + '&e=' + id; i = document.createElement('script'); i.type = 'application/javascript'; i.async = true; i.src = u; d.getElementsByTagName('head')[0].appendChild(i); }("6666", document.location.href, document));`, type: 'text/javascript' } ] }) </script>
注意事项
如果需要避免服务端渲染阶段执行该脚本引发报错,可以给script配置添加对应判断:
- Nuxt2:将script配置包裹在
if (process.client) {}判断内 - Nuxt3:给script配置项添加
client: true属性即可
内容的提问来源于stack exchange,提问作者Anusha Jain
相关产品推荐
相关产品推荐

