DFP post-rendering callback

后端 未结 6 1724
谎友^
谎友^ 2021-01-31 04:04

I need to trigger some JavaScript after DFP has finished rendering all the ads on the page - or at least when it has triggered collapseEmptyDivs (which

6条回答
  •  抹茶落季
    2021-01-31 04:26

    I'm pretty sure that DFP doesn't provide for a callback after the ad has rendered. I have used the following code to do this. It calls the callback function after one of the following has happened:

    -The ad has loaded and the iframe has rendered

    -No ad was loaded, and the ad unit was hidden by collapseEmptyDivs()

    -A certain amount of time has passed (in this case, 2 seconds) with neither one happening. Like if there was some sort of network error connecting to DFP.

    adId would be the id of your ad container

    assumes you are using jQuery

    function callback() {
       //your callback function - do something here
    }
    
    function getIframeHtml(iframe) {
       if(iframe.contentWindow && iframe.contentWindow.document && iframe.contentWindow.document.body && iframe.contentWindow.document.body.innerHTML) {
           return iframe.contentWindow.document.body.innerHTML;
       }
       return null;
    }
    
    var dfpNumChecks = 20;
    var dfpCheckCount = 0;
    var dfpCheckTimer = 100;
    
    function dfpLoadCheck(adId) {
       var nodes = document.getElementById(adId).childNodes;
    
       if(nodes.length && nodes[0].nodeName.toLowerCase() == 'iframe' && getIframeHtml(nodes[0])) {
           //the iframe for the ad has rendered
           callback();
           return;
       } else if($('#' + adId).css('display') == 'none' || (dfpCheckCount >= dfpNumChecks)) {
           //the ad unit has been hidden by collapseEmptyDivs()
           callback();
           return;
       } else {
           dfpCheckCount++;
           setTimeout(function() { dfpLoadCheck(adId) }, dfpCheckTimer); 
       }
    } 
    

提交回复
热议问题