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

如何实现Adsense广告的视口可见触发式懒加载?

Adsense 视口懒加载合规实现方案

以下实现完全符合Adsense官方政策要求,仅当广告单元进入用户可见视口才触发加载,不属于固定时长延迟加载逻辑

实现注意事项

  • 不要修改Adsense官方广告代码的核心执行逻辑,仅控制广告代码的注入与触发时机
  • 首屏默认可见区域的广告不建议使用该方案,避免影响正常广告展示收益
  • 广告占位容器需要提前设置对应宽高,避免广告加载后出现页面布局偏移

具体实现代码

1. 广告位占位HTML

<!-- 非首屏广告位占位,提前设置好对应广告位的宽高 -->
<div class="adsbygoogle-lazy" 
     data-ad-client="ca-pub-替换为你自己的发布商ID" 
     data-ad-slot="替换为对应广告位ID"
     style="display:block;width:300px;height:250px;margin:15px auto;">
</div>

2. 懒加载逻辑JS

// 标记Adsense官方脚本是否已加载,避免重复请求
let adsScriptLoaded = false;
function loadAdsenseCoreScript() {
  if (adsScriptLoaded) return;
  const adScript = document.createElement('script');
  adScript.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
  adScript.crossOrigin = 'anonymous';
  adScript.async = true;
  document.head.appendChild(adScript);
  adsScriptLoaded = true;
}

// 初始化交叉观察器监听广告位可见状态
const adLazyObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const targetAd = entry.target;
      // 替换为官方识别的广告类名
      targetAd.classList.add('adsbygoogle');
      // 加载官方脚本(仅首次触发时加载)
      loadAdsenseCoreScript();
      // 触发广告请求
      (adsbygoogle = window.adsbygoogle || []).push({});
      // 已触发加载的广告取消监听
      adLazyObserver.unobserve(targetAd);
    }
  })
}, {
  rootMargin: '200px 0px', // 广告进入视口前200px提前加载,降低用户看到空白的概率
  threshold: 0.1
})

// 批量绑定所有待懒加载的广告位
document.querySelectorAll('.adsbygoogle-lazy').forEach(adEl => {
  adLazyObserver.observe(adEl);
})

效果说明

  • 该方案基于浏览器原生IntersectionObserver实现,性能开销极低,兼容95%以上的主流浏览器
  • 广告加载触发完全匹配用户真实浏览行为,不会触发Adsense无效展示、流量作弊类的违规判定
  • 单页面多广告位场景下,Adsense核心脚本仅会加载一次,不会产生重复请求浪费资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:45:03