我正在尝试更新我的谷歌分析属性。过去我将代码放在现有的 javascript 库中。我不知道如何使用新的 gtag.js 来做到这一点
旧代码包含在现有的 javascript 文件中
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-29861433-1', 'garyjohnsoninfo.info');
ga('send', 'pageview');
放入现有的 javascript 文件时会失败
<script async src="https://www.googletagmanager.com/gtag/js?id=G-0E6CK94QYH"></script>
这是 gtag.js
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-0E6CK94QYH"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-0E6CK94QYH');
</script>
我发现这段代码对我有用(在 ChatGPT 的帮助下!)
$(document).ready( function(){
// Create the script element for Google Tag Manager
var gtmScript = document.createElement('script');
gtmScript.src = "https://www.googletagmanager.com/gtag/js?id=yourID";
gtmScript.async = true;
// Create the script element for configuring Google Analytics
var gaScript = document.createElement('script');
gaScript.textContent = `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'yourID');
`;
// Append the scripts to the head of the document
document.head.appendChild(gtmScript);
document.head.appendChild(gaScript);
});