Load Dynamic DFP tags

Loading a DFP tag on pressing a button

by Oscar Domin

HTML

<script type='text/javascript'>
    var num_inserted_banners = 0;
    function loadBanner(slotName, slotSizes, containerId) {
        googletag.cmd.push(function() {
            googletag.defineSlot(slotName, slotSizes, containerId)
                    .addService(googletag.pubads());
            googletag.pubads().enableSingleRequest();
            googletag.enableServices();
        });
        var containerDiv = document.createElement("div");
        containerDiv.id = containerId;
        containerDiv.className = "ad";
        document.body.appendChild(containerDiv);
        googletag.cmd.push(function() { googletag.display(containerId); });
        num_inserted_banners++;
    }
</script>

<button id="buttonLoader" onclick="loadBanner('/1234/Banner/', [300, 250], 'ad-' + num_inserted_banners)">Load Banner</button>

CSS

.ad {
  background-color: cadetblue;
  margin-bottom: 10px;
}

JavaScript

var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
(function() {
  var gads = document.createElement('script');
  gads.async = true;
  gads.type = 'text/javascript';
  var useSSL = 'https:' == document.location.protocol;
  gads.src = (useSSL ? 'https:' : 'http:') +
    '//www.googletagservices.com/tag/js/gpt.js';
  var node = document.getElementsByTagName('script')[0];
  node.parentNode.insertBefore(gads, node);
})();