Angular:是否动态加载Google Analytics(分析)? [英] Angular: Dynamically loading Google Analytics?

查看:87
本文介绍了Angular:是否动态加载Google Analytics(分析)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google Analytics(分析)全局网站代码(gtag.js)

I'm using Google Analytics Global site tag (gtag.js)

但是,由于trackingID是通过网络动态加载的,因此我无法直接在index.html中插入标记,因此在加载Google Analytics(分析)之前,我需要等待获取trackingID.

However, I can't directly insert the tag in index.html because the trackingID is dynamically loaded over network, so I need to wait to get the trackingID before loading Google Analytics.

为此,我创建了一个服务.

For this, I created a service.

@Injectable()
export class HelpersService {

  constructor() {}

  static loadGoogleAnalytics(trackingID: string): void {
    document.write('' +
      '<script async src=\'https://www.googletagmanager.com/gtag/js?id=' + trackingID + '\'></script>\n' +
      '  <script>\n' +
      '    window.dataLayer = window.dataLayer || [];\n' +
      '\n' +
      '    function gtag() {\n' +
      '      dataLayer.push(arguments)\n' +
      '    };\n' +
      '    gtag(\'js\', new Date());\n' +
      '\n' +
      '    gtag(\'config\', \'' + trackingID + '\');\n' +
      '  </script>');
  }
}

然后,一旦我获得了我的GA跟踪ID集,就在我的根组件中调用了此方法:

Then, once I get my GA tracking ID set, in my root component, I call this method:

HelpersService.loadGoogleAnalytics(myGATrackingID);

问题

GA已加载并正常运行(我可以看到在GA信息中心中检测到我的用户). 但是我的Angular项目根本没有加载,我有一个空白页,无限加载,检查HTML仅显示GA代码,而不显示我的Angular项目.

The issue

GA is loaded and works (I can see my user is detected in GA dashboard). But my Angular project is not loaded at all, I have a blank page, infinite loading, and inspecting HTML shows me GA code only, not my Angular project.

有什么主意吗?

推荐答案

在完全加载HTML文档后,使用document.write()将删除所有现有的HTML:

Using document.write() after an HTML document is fully loaded, will delete all existing HTML: example here

在您的情况下,我只是从<script>标记中提取函数作为定义,或者,如果您在应用启动后严格需要加载此函数,请将其提取到延迟加载的angular模块中.

In your case, I would simply extract the function from the <script> tag as a definition, or if you strictly need to load this after the app has started, extract it to a lazy-loaded angular module.

编辑-> 这是一个代码示例:

EDIT -> here is a code sample:

  static loadGoogleAnalytics(trackingID: string): void {

    let gaScript = document.createElement('script');
    gaScript.setAttribute('async', 'true');
    gaScript.setAttribute('src', `https://www.googletagmanager.com/gtag/js?id=${ trackingID }`);

    let gaScript2 = document.createElement('script');
    gaScript2.innerText = `window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag(\'js\', new Date());gtag(\'config\', \'${ trackingID }\');`;

    document.documentElement.firstChild.appendChild(gaScript);
    document.documentElement.firstChild.appendChild(gaScript2);
  }

这篇关于Angular:是否动态加载Google Analytics(分析)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆