You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Googletag如何检测无广告加载状态以展示defaultImage

实现方案

核心逻辑

通过Google Publisher Tag(GPT)原生提供的slotRenderEnded事件判断广告位填充状态:该事件会在每个广告位的广告请求返回、渲染前触发,事件参数中的isEmpty字段为true时即代表当前广告位无广告可加载,此时即可插入默认展示图。

完整示例代码

// 定义目标广告位
const targetAdSlot = googletag.defineSlot('/6355419/Travel', [250, 200], 'ad-slot-2')
    .addService(googletag.pubads());

// 注册广告渲染完成事件监听,必须放在enableServices执行前
googletag.pubads().addEventListener('slotRenderEnded', event => {
    // 匹配目标广告位,避免处理页面其他广告位
    if (event.slot.getSlotElementId() === 'ad-slot-2') {
        const adSlotDom = document.getElementById('ad-slot-2');
        // 无广告填充时展示默认图
        if (event.isEmpty) {
            // 可根据需求添加跳转链接,调整默认图尺寸与广告位一致即可
            adSlotDom.innerHTML = `
                <a href="默认广告跳转地址(可选)" target="_blank">
                    <img src="你的defaultImage资源地址" width="250" height="200" alt="广告">
                </a>
            `;
        }
    }
});

// GPT标准初始化逻辑
googletag.pubads().enableSingleRequest();
googletag.enableServices();
googletag.display('ad-slot-2');

关键说明

  • 事件监听必须在googletag.enableServices()执行前注册,否则会无法捕获首次广告加载的触发事件
  • 该方案同时兼容广告位手动刷新的场景:每次广告刷新后都会触发slotRenderEnded事件,无广告时会自动替换为默认图
  • 多广告位场景下,只需通过event.slot.getSlotElementId()匹配对应广告位ID,即可分别为不同广告位配置不同的默认展示逻辑

内容的提问来源于stack exchange,提问作者Noon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 10:18:02