为了折叠空的广告 div,在 Google 发布商代码中定义了两个专用选项:
//for all adslots on the page
googletag.pubads().collapseEmptyDivs()
//for a dedicated adslot on the page
googletag.defineSlot(...).setCollapseEmptyDiv(...).addService(googletag.pubads())
有几种配置方式:
对于页面中的所有广告位/如果为空,则在广告调用后折叠
对于页面中的所有广告位/默认折叠,如果不为空则打开
对于特定的广告位/如果为空,则在广告调用后折叠
对于特定的广告位/默认折叠,如果不为空则打开
以下示例来自official documentation:
<script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
<script>
window.googletag = window.googletag || {cmd: []};
googletag.cmd.push(function() {
// Configure all ad slots on the page to be expanded by default, but
// collapse slots that are unable to be filled with an ad.
googletag.pubads().collapseEmptyDivs();
// The above setting assumes all ad slots are likely to be filled.
// If ad slots are not likely to be filled, pass true as a parameter as
// shown below. In this configuration, slots will be collapsed by
// default and expanded only if they are able to be filled.
// googletag.pubads().collapseEmptyDivs(true);
// This slot will use the page-level settings configured above.
googletag.defineSlot('/6355419/Travel', [300, 250], 'ad-slot-1')
.setTargeting("test", "responsive")
.addService(googletag.pubads());
// Configure per-slot overrides.
// This slot will be expanded by default, but collapse if it cannot be
// filled.
googletag.defineSlot('/6355419/Travel', [250, 200], 'ad-slot-2')
.setTargeting("test", "responsive")
.setCollapseEmptyDiv(true)
.addService(googletag.pubads());
// This slot will be expanded by default and never collapse.
googletag.defineSlot('/6355419/Travel', [200, 150], 'ad-slot-3')
.setTargeting("test", "responsive")
.setCollapseEmptyDiv(false)
.addService(googletag.pubads());
// This slot will be collapsed by default and only expand if it can be
// filled.
googletag.defineSlot('/6355419/Travel', [150, 100], 'ad-slot-4')
.setTargeting("test", "responsive")
.setCollapseEmptyDiv(true, true)
.addService(googletag.pubads());
// Enable SRA and services.
googletag.pubads().enableSingleRequest();
googletag.enableServices();
});
</script>
这很好用,不需要自己手动隐藏广告位。