The idea of Google DFP is very much needed feature. Every content rich websites should consider lazy loading of the Google DFP ads.
Notice that we have a class called "adunit-lazy" on the adunit element that we will target in our JavaScript. The above adunit is not visible as soon as the site loads. When the user scrolls down and the adunit gets visible we will load the ad.
Lets detect when the adunit is visible when user scrolls. Following is the code that detets the adunit is visible:
If you are not sure about isElementVisibleOnViewport method, get it from here
Now all we need is to define applyAdLoad method. Once the ad is loaded we are removing the class "anunit-lazy" to make sure the ad is loaded once for a particular slot. If we load it multiple times then we will get into Exception in queued GPT command error.
Following is the applyAdLoad function definition
Why we need lazy loading of DFP ads?
The concept of lazy loading of Google DFP ads is to minimize the load time during the page load.Cases where we need lazy loading of DFP ads
If we have DFP ads that are in the bottom of the page and not visible in the viewport as soon as the page loads, those ads should be lazy loaded.Sample code for lazy loading ads
Let say we have the following ad that we want to lazy load:
<div class="adunit-lazy" id="banner" data-name="banner" data-size-mapping="sizemapping"></div>
Notice that we have a class called "adunit-lazy" on the adunit element that we will target in our JavaScript. The above adunit is not visible as soon as the site loads. When the user scrolls down and the adunit gets visible we will load the ad.
Lets detect when the adunit is visible when user scrolls. Following is the code that detets the adunit is visible:
$(window).scroll(function() { $('.adunit-lazy').each(function() { if($(this).isElementVisibleOnViewport()){ $(this).applyAdload(); $(this).removeClass("adunit-lazy"); } }); });
If you are not sure about isElementVisibleOnViewport method, get it from here
Now all we need is to define applyAdLoad method. Once the ad is loaded we are removing the class "anunit-lazy" to make sure the ad is loaded once for a particular slot. If we load it multiple times then we will get into Exception in queued GPT command error.
Following is the applyAdLoad function definition
$.fn.applyAdload = function(){ if (window.googletag && googletag.apiReady){ var adunitID = $(this).attr('id'); googletag.cmd.push(function() { var adSlot = googletag.defineSlot('/'+<dfpid> +'/' + adunitID, [], adunitID); if(adSlot != null) { var map = googletag.sizeMapping(); map.addSize([1024, 768], [970, 250]); adSlot.defineSizeMapping(map.build()).addService(googletag.pubads()); googletag.pubads().refresh([adSlot]); } }); } };
Comments
Post a Comment