javascriptjqueryhtmlgoogle-dfp

Moving DFP ads post document load


We have a responsive site with a content area and sidebar. The sidebar goes below the content area when the site responds or is loaded on a mobile. The issue is that the mrec at the top of the sidebar is now far too low on the page and we need to make it higher in the dom.

So, pre render I pop a few divs in like this

<div class="ad-inject-ad ad-mrec2"></div>

That can be mrec1 through 3 depending on page, position, etc.

I also wrap my sidebar mrecs in identifiable classes, eg ad-medrec2 so I can then move them when on mobile

$('.sidebar .ad-medrec2').appendTo('.ad-inject-ad.ad-mrec2')

This works a charm.

BUT, 60 - 70% of the time the ads disappear. The structure remains, you can see the container div is 300+ px tall where the ad should be, but the ad is gone.

I've tried using the refresh() method in DFP as well as the display() method. It seems though that the ad is displayed, but not visible. I lose the visibility on the ad, not the ad itself.

I've read that this can be caused by iframe's and their inability to reset state. But, I'm not sure the state needs to be refreshed.

And, why does it all work a third of the time?

What can I do here?

EDIT

I've also looked at the DFP jQuery plugin but would prefer to not load another script if it can be avoided.


Solution

  • So, I have this working at quite a high success rate now.

    Firstly, I move the ad.

    $('.sidebar .ad-medrec2').appendTo('.ad-inject-ad.ad-mrec2');
    

    Then, I work out what the ad container's id and slot is called, delete the contents of the div and call the googletag function again to repopulate.

    mrec2_id = $('.ad-medrec2').attr('id');
    mrec2_slot_name = mrec2_id.substr(0, mrec2_id.indexOf('-wrapper'))
    $('#' + mrec2_slot_name).children().remove();
    googletag.cmd.push(function() {
      googletag.display(mrec2_slot_name);
    });
    

    This is working well. BUT, I'm afraid of this loading the ad twice. Until I can come up with a better option, I'll continue doing this.