Last active
November 12, 2020 15:26
-
-
Save martinsvoboda/b7a7040031f3c199278830008673f0af to your computer and use it in GitHub Desktop.
Lazyloading of Adsense ads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<ins class="adsbygoogle-lazy" | |
style="display:block" | |
data-ad-client="..." | |
data-ad-slot="..." | |
data-ad-format="auto" | |
data-full-width-responsive="true"></ins> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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