Google AdSense 动态 JS 调用与自适应布局实现

作者:青柠时间:2026-10-23 21:01:13浏览:405

本文介绍了一种通过 JavaScript 动态创建广告单元并异步加载 adsbygoogle.js 的 Google AdSense 调用方法。该方法支持在页面加载后根据设备类型(如非移动端)动态生成横幅和矩阵广告位,并自动处理脚本注入与实例化,适用于需要灵活控制广告显示时机和布局的前端场景。

Google AdSense 动态 JS 调用实现

本文介绍一种 Google 广告的非传统调用方式。


function addGoogel (content, obj) {
 addScript('//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', function () {
  var ins = document.createElement('ins')
  ins.setAttribute('class', 'adsbygoogle')
  ins.setAttribute('data-ad-client', 'ca-pub-******')
  ins.setAttribute('style', obj.style)
  ins.setAttribute('data-ad-slot', obj.slot)
  content.appendChild(ins)
  var inlineScript = document.createElement('script')
  inlineScript.type = 'text/javascript'
  inlineScript.text = '(adsbygoogle = window.adsbygoogle || []).push({});'
  document.getElementsByTagName('body')[0].appendChild(inlineScript)
 })
}

具体调用逻辑如下:


window.onload = function () {
 var line = document.getElementById('ad_line'), // 横幅
  area = document.getElementById('ad_area')// 矩阵
 if (!isYd()) { // 不为移动端

  if (line) { //横幅
   addGoogel(line, {
    style: 'display:inline-block;width:1100px;height:160px',
    slot: '6183651273'
   })
 }
  if (area) { //矩形
   addGoogel(area, {
    style: 'display:inline-block;width:250px;height:250px',
    slot: '1995310048'
   })
  }
 }
}

关于 Google 广告通过 JavaScript 动态调用的实现细节已介绍完毕。如需了解更多 JS 与 Google 广告相关的内容,建议查阅本站历史文章或继续阅读后续章节,感谢支持。

作者最新文章