首页 > 解决方案 > Gtag 未定义

问题描述

尝试使用没有脚本标签的 Javascript 添加 Gtag 脚本和一些转化跟踪代码。我在控制台中得到gtag 未定义和 appendChild 的 null错误。

Gtag脚本如下

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

  gtag('config', 'AW-xxxxxx');
</script>

这就是我尝试实现 gtag 脚本和转换代码的方式。

// Create gtag Script
var gtagScript = document.createElement("script");
gtagScript.type = "text/javascript";
gtagScript.setAttribute("async", "true");
gtagScript.setAttribute("src", "https://www.googletagmanager.com/gtag/js?id=AW-xxxxxx");
document.head.appendChild(gtagScript);

// Add gtag config
gtagScript.onload = function() {
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'AW-xxxxxx');
};

// Add gtag conversion pixel
gtag('event', 'conversion', {
      'send_to': 'AW-xxxxxx/hdyesanxalasis',
      'value': BOLD.order.total / 100,
      'currency': 'BOLD.order.currency',
      'transaction_id': 'BOLD.order.id'
  });

// Get order items
var content_ids = [];
BOLD.order.line_items.forEach(function(item, i){
content_ids[i] = "" + item.platform_product_id;
})

标签: javascript

解决方案


这对我有用。我删除.setAttribute("async", "true");了转换像素,然后将其包装在 onload 事件中:gtagScript.onload = function() {};

// Create gtag Script
var gtagScript = document.createElement("script");
gtagScript.type = "text/javascript";
gtagScript.setAttribute("src", "https://www.googletagmanager.com/gtag/js?id=AW-xxxxxx");
document.head.appendChild(gtagScript);


//Make sure gtag script above is loaded
gtagScript.onload = function() {

// Add gtag config
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'AW-xxxxxx');


// Add gtag conversion pixel
gtag('event', 'conversion', {
      'send_to': 'AW-xxxxxx/hdyesanxalasis',
      'value': BOLD.order.total / 100,
      'currency': 'BOLD.order.currency',
      'transaction_id': 'BOLD.order.id'
  });

// Get order items
var content_ids = [];
BOLD.order.line_items.forEach(function(item, i){
content_ids[i] = "" + item.platform_product_id;
})

};

推荐阅读