简体   繁体   English

Nuxt.js中的条件模块加载

[英]Conditional module loading in Nuxt.js

I have a module for Google Tag Manager in my Nuxt.js config, like so: 我的Nuxt.js配置中有一个用于Google跟踪代码管理器的模块,如下所示:

modules: [
  [
    '@nuxtjs/google-tag-manager',
    {
      id: 'GTM-XXXXXXX'
    }
  ]
]

This is working fine but I am wondering how I can conditionally load this module based on the value of a cookie set by the site? 这工作正常,但我想知道如何根据网站设置的cookie值有条件地加载此模块?

We have a mechanism by which the user can select certain cookies to accept or deny and a part of that is to block tracking scripts. 我们有一种机制,用户可以通过该机制选择接受或拒绝某些cookie,其中一部分是阻止跟踪脚本。

Is there any recommended way to do this with modules or scripts loaded via the config? 是否有任何建议的方法来通过配置加载模块或脚本? Ideally, it would be possible to then load these should the values within the cookies change in the future as well. 理想情况下,如果cookie中的值在将来发生变化,则可以加载这些。

Any help or pointers are greatly appreciated. 非常感谢任何帮助或指示。

To execute GTM conditionally you have to drop the @nuxtjs/google-tag-manager and implement it yourself as a plugin. 要有条件地执行GTM,您必须删除@nuxtjs/google-tag-manager并将其作为插件@nuxtjs/google-tag-manager实现。 NUXT docs are really awesome and have you covered on this too. NUXT文档非常棒,你也可以了解它。 I used this resource for implementation and ended up with this code: 我使用此资源进行实现,最终得到了以下代码:

// app/plugins/gtm.js

import Cookies from 'js-cookie'

const gtmKey = 'GTM-XXXXX' // <- insert your GTM key here

export default () => {
  /*
  ** Only run on client-side and only in production mode
  */
  if (process.env.NODE_ENV !== 'production') return
  /*
  ** Only run if it's not prevented by user
  */
  if (Cookies.get('disable-gtm')) return
  /*
  ** Include Google Tag Manager
  */
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
      new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  })(window,document,'script','dataLayer', gtmKey)
}

Basically you allow the user to set a custom cookie ( disable-gtm in my case) and check this cookie in the gtm.js plugin. 基本上,您允许用户设置自定义cookie(在我的情况下为disable-gtm )并在gtm.js插件中检查此cookie。 If it's there and valid, skip everything GTM related. 如果它存在且有效,请跳过GTM相关的所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM