Angular2根据环境使用不同的GTM容器

时间:2017-10-25 10:41:07

标签: angular google-tag-manager

我使用谷歌标记管理器(GTM)管理角度应用程序中的标记,如下所示:

<html lang="en">
  <head>
    <base href="/">
    <title>Angular Tour of Heroes</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Google Tag Manager -->
    <script>(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','GTM-WAHOCA');</script>
    <!-- End Google Tag Manager -->
  </head>
  <body>
    <!-- Google Tag Manager (noscript) -->
    <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-WAHOCA"
      height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <!-- End Google Tag Manager (noscript) -->
    <my-app>Loading...</my-app>
  </body>
</html>

现在我想根据环境使用不同的GTM容器,如开发,生产环境等。上面的代码只是使用了&#39; GTM-WAHOCA&#39;容器ID通过硬编码。
如何根据index.html中的环境配置使用不同的GTM容器?这意味着我想在文件中方便地管理GTM容器ID。或者,还有其他方法可以达到我的要求吗?

参考文献:
1。Is there a way to conditionally include scripts in index.html as in analytics?
2。Conditional template logic in index.html for beta.11-webpack
3。Feature Request: load scripts in angular-cli.json conditionally?

3 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

几周前我做了一个similar question,我认为它可以在这里有效!

document.getElementById("myScript").remove();
var testScript = document.createElement("script");
testScript.setAttribute("id", "myScript");
testScript.setAttribute("src", "assets/js/script.js");
document.body.appendChild(myScript);

答案 2 :(得分:0)

main.ts

import { enableProdMode } from '@angular/core';

import { env } from './environments/environment';

if (env.production) {

  // add Google Analytics script to 

<head>
  const script = document.createElement('script');
  script.innerHTML = `(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','GTM-XXXXXXX');`;

  document.head.appendChild(script);


  // disable Angular development mode

  enableProdMode();
}