Skip to content

Instantly share code, notes, and snippets.

@martinsvoboda
Last active November 12, 2020 15:26
Show Gist options
  • Save martinsvoboda/b7a7040031f3c199278830008673f0af to your computer and use it in GitHub Desktop.
Save martinsvoboda/b7a7040031f3c199278830008673f0af to your computer and use it in GitHub Desktop.
Lazyloading of Adsense ads
<ins class="adsbygoogle-lazy"
style="display:block"
data-ad-client="..."
data-ad-slot="..."
data-ad-format="auto"
data-full-width-responsive="true"></ins>
function get_ad_observer() {
if (window.ad_observer) {
return window.ad_observer;
}
window.ad_observer = new IntersectionObserver(function (entries, observer) {
[].forEach.call(entries, function (entry) {
if (entry.isIntersecting) {
observer.unobserve(entry.target);
if (entry.target.classList.contains('adsbygoogle-lazy')) {
entry.target.classList.remove('adsbygoogle-lazy');
if (!entry.target.classList.contains('adsbyhb')) {
entry.target.classList.add('adsbygoogle');
(window.adsbygoogle = window.adsbygoogle || []).push({});
}
}
}
});
}, {
rootMargin: "500px", // config: load 500px before ad
});
return window.ad_observer;
}
function init_adsense_lazy_load(doc) {
var ad_observer = get_ad_observer();
// call this
var ad_units = doc.querySelectorAll('.adsbygoogle-lazy');
[].forEach.call(ad_units, function (entry) {
ad_observer.observe(entry);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment