簡體   English   中英

其他加載完成后,使用Webpack加載Google Analytic的gtag.js

[英]Loading Google Analytic's gtag.js using Webpack after everything else loads

如果我按照他們的建議加載Google Analytics(分析),則一切正常:

<head>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-123"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-123');
</script>

但是,我想在其他所有內容加載並運行后再加載GA。 我的項目使用Webpack和React,所以我想在React掛載后使用Webpack的動態導入:

initGoogleAnalytics.js:

import { GA_ID } from 'settings';

export default () => {
  window.dataLayer = window.dataLayer || [];
  window.gtag = (...args) => window.dataLayer.push(args);
  window.gtag('js', new Date());
  window.gtag('config', GA_ID);

  if (process.env.NODE_ENV === 'production') {
    const script = window.document.createElement('script');
    script.async = 1;
    script.src = `https://www.googletagmanager.com/gtag/js?id=${GA_ID}`;
    const elem = window.document.getElementsByTagName('script')[0];
    elem.parentNode.insertBefore(script, elem);
  }
};

零件:

componentDidMount() {
  initGoogleAnalytics();
}

但是,這不會記錄任何內容。 除了加載gtag/js之外,它也不會發出任何網絡請求。

React安裝后如何加載GA?

我發現了問題。 Google Analytic的代碼為:

function gtag(){dataLayer.push(arguments);}

我將其更改為:

window.gtag = (...args) => dataLayer.push(args);

但是,GA需要一個arguments對象,因為它使用arguments.callee

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM