I have added the following code to my webpage to send event info to Google Analytics:
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-144340016-1"></script>
<!-- Google Analytics -->
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'UA-144340016-1');
</script>
<!-- End Google Analytics -->
</head>
<body>
<a id='lin1' href="cool.com" onclick="gtag('event', 'click', {'event_category': 'cat1', 'event_label': 'lab1'});">
</a>
</body
Now I don't want to use the inline onclick
event on the html and I want to move this bit to a separate JavaScript code, so something like this:
my.js
$('#lin1').click(function() {
gtag('event', 'click', {'event_category': 'cat1', 'event_label': 'lab1'});
});
An then add my.js at the bottom of my webpage. Is there any issue with this approach? All the documentations that I have seen add the gtag
event directly to the HTML, that's why I wanted to make sure if there is no downside with what I am doing
There is no problem with having a function library with function that send hits to Analytics. Eventually the documentation suggests inserting the snippet (gtag.js
) directly into the HTML, in the head
(but this looks like you already do).