javascript - 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;
})
解决方案
这对我有用。我删除.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;
})
};
推荐阅读
- security - 在 MAMP 上更新 CA 证书包
- java - 如何使用 java 8 流将多维字符串数组(String[][])转换为多维双精度数组(double[][])?
- css - 试图在 CSS 中编写关于 Turbo 主题/Shopify 的媒体查询但它不起作用?
- php - 需要帮助将 HTML 和 PHP 块转换为我可以随意调用的变量/函数
- powerbi - 是否可以在 PBI 卡视觉中具有 2 种不同的字体大小
- python - 为“警告”设置异常断点
- charts - echart为xAxis.axisLabel的富文本的不同部分绑定不同的点击事件处理程序?
- react-native - React Native:react-native-toggle-element 不起作用
- c# - 如何更新form2中的数据而不创建form2的新实例
- python - (Python,Panda)重新排序标题及其各自的子标题