How to catch error in googletag.cmd.push(function() { googletag.display('div-id'); });?

708 Views Asked by At

I am trying to catch the error on
 googletag.cmd.push(function() { googletag.display('div-id'); });

While I know the root of the problem is because the slot is not defined in the head, how can I catch the error? I'm facing a problem where the definedSlot is messy and all over the place so I think catching the error in the googletag.cmd.push would be an easier solution.
Thank you.
1

There are 1 best solutions below

0
rabsom On

you can check wether the targeted ID in the googletag defined slots exists in the DOM before displaying it :

    //get all the defined slots
    var definedSlots = googletag.pubads().getSlots();
    //loop through the definedSlots
    for (var x = 0; x < definedSlots.length; x++) {
       //retrieve the targeted ID
       var slotId = definedSlots[x].getSlotId().getDomId();
       //if it exists
       if (document.querySelector('#'+ slotId)) {
          //then dislay it
          googletag.cmd.push(function() { googletag.display(slotId); });
       }
     }