SomewhereDave SomewhereDave - 1 year ago 82
Javascript Question

How to make GTM Tags wait for some jQuery to be loaded?

I would like to track if a toast (or any "popup element") gets displayed using Google Analytics Event Tracking via GTM.
Whether or not the toast gets displayed is defined by jQuery code and based on cookie information like so

function ShowToast(Msg){
$('#toast').animate({ left: '-10px' });

called by

<script type="text/javascript">
$(function() {
ShowToast("SOME HTML");

This is what I got in GTM so far using a custom variable

if(document.querySelector("#toast #toast-msg").length > 0){
return true;

with a trigger listening for this variable to be true and the usual Universal Analytics Event Tag. The idea is to simply check if the toast-msg is shown or not, which works fine in preview mode.

Now to the problem: The tag is listening to gtm.js (pageview), but the jQuery code from the toast might load only after gtm.js is ready. Hence, sometimes the toast is not yet displayed when the tracking code is ready to fire and the event is not recorded.

Is there a way to use GTM and Javascript / JQuery to make sure all JQuery is loaded before GTM variables/triggers/tags are resolved? Or a completly different approach?

Answer Source
  1. Make Sure you have the dataLayer initialized in the <head> of your document by including this line of code: <script>window.dataLayer = window.dataLayer || [];</script>
  2. Add this code to your jQuery toasts (or whatever else you want to track) dataLayer.push({'event': 'event_name'});
  3. Create a Custom Event trigger in GTM with the event_name you chose above.
  4. Create a GA Tag of type event with the above trigger
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download