Coding / Programming Videos

Post your favorite coding videos and share them with others!

Bye bye (not set)’s, hello values! – Rameez Kakodker – Medium

Source link

Or how to ensure your tags and scripts are fired every time they’re triggered.

Ever write a tag on GTM to say, fire a GA event, and you get slightly less than expected hits? And you’ve done your due diligence and checked everything, employed the scientific method of reduction and isolation of the problem and nothing comes up? Well, this may come as a surprise, but that innocent little piece of code you’ve written to trigger the GA event may be the culprit! Surprised? Suspicious? Read on…

The GTM Tags

Let’s assume you’ve to track the number and product ids in the shopping cart. So you go ahead and make a GTM tag that triggers on the cart page. Being a smart product manager, you decide to separate out the data capture and event trigger. Your first tag (to capture the data) looks something like this:

//using https://www.toysrusmena.com as example
$(function(){
jQuery(“.b-cart-products > div”).each(function(i,v){
console.log(jQuery(v).attr(“data-tau-pid”)); //gets all the pids
//add values to variable
});
dataLayer.push(variable); //add values to data layer
});

This is created as an HTML tag. The second tag is the event tag (assuming you’ve done the variable assignment etc.).

The next step you take is to test it — preview across multiple browsers and devices and it works! Easy peasy lemon squeezy.

The problem

Large (not set) volumes!

Where are these (not set) coming from? You’ve already excluded empty cart page — so where is the problem?

Let’s look at the JS — your first function is the $(function() which is essentially jQuery’s document.ready event handler. jQuery as you know, has to be called from an external source (your servers, google servers, servers of that one site you copied your code from :P). Any many a times, it may not load or not load in time, causing you to get this error in the console:

$ (or jQuery) not defined.

And this is the reason why your variables don’t get set and hence you get (not set).

The fix

Going old school — use plain Javascript to ensure that the document is loaded and then call the function:

window.onload = function(){
jQuery(“.b-cart-products > div”).each(function(i,v){
console.log(jQuery(v).attr(“data-tau-pid”)); //gets all the pids
//add values to variable
});
dataLayer.push(variable); //add values to data layer
}

You can read all about the debates between window.onload vs document.ready here, here and here.

Source link

Bookmark(0)
 

Leave a Reply

Please Login to comment
  Subscribe  
Notify of
Translate »