How to load ad using Google Publisher Tag?

If we are thinking about dynamically build ad requests then Google Publisher Tag (GPT) is the best solution. Google Publisher Tag (GPT) is an ad tagging library from Google.

If we can configure all the necessary parts of an ad such as ad unit code, ad size, ad targeting, etc., it displays the ad on web pages.

Following is the code snippet that we can use to display an ad using GPT.

Code for head tag

Add the following code snippet in the HTML head tag of your webpage.

    <script async src='https://securepubads.g.doubleclick.net/tag/js/gpt.js'></script>
    <script>
      window.googletag = window.googletag || {cmd: []};
      googletag.cmd.push(function() {

        googletag.defineSlot('/6355419/topbanner', [[1020,300]], 'div-gpt-ad-8958584-1')
                .addService(googletag.pubads());
        googletag.pubads().setTargeting('urlQuery', ['test:standard']);
        googletag.enableServices();
      });
    </script>

Code for body tag

Add the following code snippet in the HTML body tag of your webpage.

    <div id='div-gpt-ad-8958584-1'>
      <script>
        googletag.cmd.push(function() { googletag.display('div-gpt-ad-8958584-1'); });
      </script>
    </div>