【问题标题】:Nuxt: Inside a plugin, how to add dynamic script tag to head?Nuxt:在插件内部,如何在头部添加动态脚本标签?
【发布时间】:2019-06-08 00:26:09
【问题描述】:

我正在尝试为 Nuxt 构建一个 Google Analytics 插件,该插件将从 CMS 获取跟踪 ID。我想我真的很接近了。

我只在客户端加载了一个插件文件。该插件通过plugins:[{ src: '~/plugins/google-gtag.js', mode: 'client' }] 数组从nuxt.config.js 加载。

从那里开始,主要问题是 gtag 脚本在其 URL 中需要 UA 代码,因此我不能将其添加到 nuxt.config.js 中的常规脚本对象中。我需要从商店获取那些 UA 代码(水合形式 nuxtServerInit

所以我在插件中使用head.script.push 在 URL 中添加带有 UA 代码的 gtag 脚本。但这不会导致在第一页加载时添加脚本,但它会用于所有后续页面转换。很明显,我在页面渲染中运行 head.script.push 为时已晚。

但我不知道如何获取跟踪 ID,然后将脚本添加到头部。

// plugins/google.gtag.client.js with "mode": "client
export default ({ store, app: { head, router, context } }, inject) => {
    // Remove any empty tracking codes
    const codes = store.state.siteMeta.gaTrackingCodes.filter(Boolean)

    // Add script tag to head
    head.script.push({
        src: `https://www.googletagmanager.com/gtag/js?id=${codes[0]}`,
        async: true
    })
    console.log('added script')

    // Include Google gtag code and inject it (so this.$gtag works in pages/components)
    window.dataLayer = window.dataLayer || []
    function gtag() {
        dataLayer.push(arguments)
    }
    inject('gtag', gtag)
    gtag('js', new Date())

    // Add tracking codes from Vuex store
    codes.forEach(code => {
        gtag('config', code, {
            send_page_view: false // necessary to avoid duplicated page track on first page load
        })

        console.log('installed code', code)

        // After each router transition, log page event to Google for each code
        router.afterEach(to => {
            gtag('event', 'page_view', { page_path: to.fullPath })
            console.log('afterEach', code)
        })
    })
}

【问题讨论】:

  • 如果你查看nuxt-community/google-tag repo,它使用模块来执行脚本推送,因为模块是在插件之前构建的。
  • @Ohgodwhy 是的,这实际上就是我从那里得到的。那么我需要一个插件和一个模块吗?不能仅仅作为插件来做到这一点吗?我也不确定模块是否可以访问商店。
  • 确实!该模块将在生命周期中比插件更早地触发,允许您注入头部预编译,而插件执行后编译预捆绑,这很可能是您遇到此问题的原因。
  • @Ohgodwhy 谢谢。关于如何访问模块中的商店的任何提示?
  • 我也有同样的问题。你找到解决方案了吗?

标签: vue.js nuxt.js head gtag.js


【解决方案1】:

我最终得到了这个工作,我们在 production here 中使用它。

撰写本文时的代码如下所示:

export default ({ store, app: { router, context } }, inject) => {
    // Remove any empty tracking codes
    let codes = _get(store, "state.siteMeta.gaTrackingCodes", [])
    codes = codes.filter(Boolean)

    // Abort if no codes
    if (!codes.length) {
        if (context.isDev) console.log("No Google Anlaytics tracking codes set")
        inject("gtag", () => {})
        return
    }

    // Abort if in Dev mode, but inject dummy functions so $gtag events don't throw errors
    if (context.isDev) {
        console.log("No Google Anlaytics tracking becuase your are in Dev mode")
        inject("gtag", () => {})
        return
    }

    // Abort if we already added script to head
    let gtagScript = document.getElementById("gtag")
    if (gtagScript) {
        return
    }

    // Add script tag to head
    let script = document.createElement("script")
    script.async = true
    script.id = "gtag"
    script.src = "//www.googletagmanager.com/gtag/js"
    document.head.appendChild(script)

    // Include Google gtag code and inject it (so this.$gtag works in pages/components)
    window.dataLayer = window.dataLayer || []
    function gtag() {
        dataLayer.push(arguments)
    }
    inject("gtag", gtag)
    gtag("js", new Date())

    // Add tracking codes from Vuex store
    codes.forEach(code => {
        gtag("config", code, {
            send_page_view: false // Necessary to avoid duplicated page track on first page load
        })

        // After each router transition, log page event to Google for each code
        router.afterEach(to => {
            gtag("config", code, { page_path: to.fullPath })
        })
    })
}

如果不在插件中,这是一本关于如何加载 3rd 方脚本的好书:How to Load Third-Party Scripts in Nuxt.js

【讨论】:

猜你喜欢
  • 2022-11-23
  • 1970-01-01
  • 2012-10-10
  • 2023-01-04
  • 1970-01-01
  • 2015-06-30
  • 2010-12-16
  • 2023-03-16
  • 1970-01-01
相关资源
最近更新 更多