Javascript: Dynamically generated functions, referring to an external included JS File with GPT rendering

152 Views Asked by At

Thanks for looking at this. I think I am making a conceptional mistake in my thoughts, that's why I will let you know about my scenario first:

I have 1 or x DIVs where I display DFP AdUnits and will use these dynamically generated functions on. The function triggers as soon as the DIV is in a visible area:

  1. I generate the links dynamically

  function scriptincluder(divid){
    var gbgscript = document.createElement('script');
    gbgscript.async = true;
    gbgscript.type = 'text/javascript';
    gbgscript.src = 'https://anyscript.net/script.js?function=myfmydiv1&div=mydiv1 ';
    var node = document.getElementsByTagName('script')[0];
    node.parentNode.insertBefore(gbgscript, node);
  }

With this function I dynamically create the link and this works so far. So I generate links for myfmydiv1/div1, myfmydiv2/div2, myfmydiv3/div3… so on. And add them to the parentNode.

  1. I generate the AdSlots dynamically

 googletag.cmd.push(function() {
        for (var slot in divslots) {
                window['slot_'.concat(slot.toString())] = googletag.defineSlot('/Adslot/Adslot/Adslot/Adslot/Adslot/Adslot', slotsize[slot], slot.toString()).addService(googletag.pubads());

                // generate external link pixel from #1:
                scriptincluder(slot.toString());
        }
        googletag.pubads().enableSingleRequest();
        googletag.pubads().disableInitialLoad();  // ad unit will not render yet
        googletag.enableServices();
    });

In this part I generate the Ad Units and add it to a global variable "window['slot_'.concat(slot.toString())]" (<== I have seen this on the web and I am curious if that's the right way to go. At least I can see it in the GCR dev. tool)

  1. I generate the functions referring to the link at #1 dynamically.

  for (var slot in divslots) {
    var [‘myf’ + escape(slot)] = function() { 
        alert("I am: " + slot);
        googletag.cmd.push(function() {
            googletag.pubads().refresh([window['slot_'.concat(key2.toString())]]);});
    }
  }

The function is triggered once the DIV slot is in a visible area and refreshes the Ad Unit.

It always triggers the wrong function. For example, div1 triggers function of div2 and div1 doesn’t actually load, but div2. Any ideas/help?

1

There are 1 best solutions below

0
On BEST ANSWER

I figured out the solution with an experienced programmer colleague of mine. He suggested to use the cont variable for the variable function in the last piece of code.

  for (var slot in divslots) {
    
    const myFunction = 'myf' + escape(slot);
    const mySlot = 'slot_'.concat(slot.toString());
  
    var [myFunction] = function() { 
        alert("I am: " + slot);
        googletag.cmd.push(function() {
            googletag.pubads().refresh([window[mySlot]]);});
    }
  }