You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NuxtLink跳转时页面脚本未加载的问题求助

问题分析

你遇到的核心问题是:Nuxt作为单页应用(SPA),通过NuxtLink跳转时不会刷新整个页面,页面根组件的顶层script代码只会在首次加载时执行一次,后续跳转不会重新触发脚本创建逻辑;同时直接动态插入脚本没有做重复加载校验,容易引发冲突或失效。

解决方案

1. 封装脚本加载工具函数+组件生命周期钩子

先写一个复用性强的脚本加载工具,避免重复插入脚本:

// ~/utils/loadScript.js
export const loadScript = (src, uniqueId) => {
  // 先检查脚本是否已存在,避免重复加载
  if (document.getElementById(uniqueId)) {
    return Promise.resolve()
  }
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.src = src
    script.id = uniqueId
    script.onload = resolve
    script.onerror = reject
    document.head.appendChild(script)
  })
}

然后在页面组件的生命周期钩子中调用,确保每次组件挂载时执行脚本加载:

import { butter } from "~/plugins/buttercms";
import { loadScript } from "~/utils/loadScript";

export default {
  async mounted() {
    // 先获取ButterCMS数据,再加载页面专属脚本
    await butter.page.retrieve("*", "simple-page")
    await loadScript("../../script/post-informations.js", "post-info-script")
    
    // 加载第三方全局脚本,同样做去重处理
    await loadScript("https://sibforms.com/forms/end-form/build/main.js", "sib-form-script")
  },
  // 若页面脚本是专属的,离开页面时可移除避免冲突(全局脚本可跳过)
  beforeUnmount() {
    const postScript = document.getElementById("post-info-script")
    if (postScript) document.head.removeChild(postScript)
  }
}

2. Nuxt 3 专属方案:用官方useHeadAPI

如果是Nuxt 3项目,直接用官方提供的useHead管理脚本,它会自动适配SPA跳转场景:

import { butter } from "~/plugins/buttercms";
import { useHead } from "#imports";

export default {
  async mounted() {
    await butter.page.retrieve("*", "simple-page")
    // 数据加载完成后动态注入脚本
    useHead({
      script: [
        {
          src: "../../script/post-informations.js",
          id: "post-info-script"
        },
        {
          src: "https://sibforms.com/forms/end-form/build/main.js",
          id: "sib-form-script"
        }
      ]
    })
  }
}

额外注意事项

  • 必须给每个脚本设置唯一id,用来判断是否已加载,避免重复插入导致的逻辑冲突或性能浪费
  • 如果你的组件开启了keep-alive缓存,需要在activated钩子中也执行脚本加载逻辑,确保组件从缓存激活时脚本正常运行

内容的提问来源于stack exchange,提问作者MH info

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 22:55:17