将Delay JS技术应用于AdSense以提高PageSpeed Insights分数

当经常提到 AdSense 时,您会害怕将其附加到您的网站上。因为它会影响网站加载速度并降低Google的PageSpeed Insights得分。
此后,网站在搜索引擎上的排名也有所下降。
使用权 页面速度见解 或 Chrome 浏览器中的 Lighthouse 工具,用于在 AdSense 未优化时检查网站速度。
请改用 AdSense 提供的嵌入代码。我将使用该技术 setTimeout
在 JavaScript 中延迟执行以下 AdSense 代码 3.5秒.
Delay JS 的权衡是,如果你的页面浏览量小于“3.5 秒+页面加载秒”,广告收入将不可避免地减少。
对于单位广告,您只需粘贴标签 <ins>
到要显示的位置,无需添加 <script>
.
以下是带有执行 AdSense 的 Delay 函数的 JavaScript 代码:
window.addEventListener("load", () => {
setTimeout(function () {
// Load adsbygoogle.js after 3,5s
var script_adsense = document.createElement('script');
// Replace "src" with the url provided for you by AdSense
script_adsense.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-YOURCODE';
script_adsense.setAttribute('crossOrigin', 'anonymous');
document.body.appendChild(script_adsense);
// Push multiple Ads
jQuery('.adsbygoogle').each(function () { (adsbygoogle = window.adsbygoogle || []).push({}); });
}, 3500);
});
您可以将此代码应用于 Google AdSense 提供的所有广告类型,包括“自动广告”和“广告单元”,而无需重复这些功能 push({})
.
您可以使用插件 Code snippets
将此代码粘贴到页面底部的结束标记之前 </body>
以确保广告完整展示。
这就是我将 AdSense 延迟代码放入 Oxygen Builder 中的方式。
在编写本教程的过程中。让我想起了 JavaScript 的事件捕获功能。
于是开始重写代码并测试速度。令人惊讶的是,这种方法获得了与 3.5 秒延迟相同的绝对分数,但在用户交互时广告仍然提前加载。
因为我使用 Wordpress 并且预加载了 jQuery 文件,所以我编写了 jQuery 代码以使其简短:
jQuery(window).one("touchmove.adsense mousemove.adsense scroll.adsense", () => {
// Load adsbygoogle.js
var script_adsense = document.createElement('script');
// Replace "src" with the url provided for you by AdSense
script_adsense.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-YOURCODE';
script_adsense.setAttribute('crossOrigin', 'anonymous');
document.body.appendChild(script_adsense);
// Push multiple Ads
jQuery('.adsbygoogle').each(function () { (adsbygoogle = window.adsbygoogle || []).push({}); });
// Turn off events
jQuery(window).off(".adsense");
});
完成后并对两种方式的结果进行评分 100/100 就像未连接 AdSense 时一样。
相关文章