Untitled
unknown
plain_text
10 months ago
1.5 kB
4
Indexable
// Define a function to check if an element is in the viewport
function isElementInViewport(el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
// Define a function to handle lazy loading
function lazyLoadAds() {
var ads = document.querySelectorAll('.lazy-ad');
ads.forEach(function(ad) {
if (isElementInViewport(ad)) {
googletag.cmd.push(function() {
googletag.display(ad.id);
});
ad.classList.remove('lazy-ad');
}
});
}
// Use Intersection Observer to trigger lazy loading
var observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var ad = entry.target;
googletag.cmd.push(function() {
googletag.display(ad.id);
});
observer.unobserve(ad);
ad.classList.remove('lazy-ad');
}
});
});
// Start observing lazy ads
var lazyAds = document.querySelectorAll('.lazy-ad');
lazyAds.forEach(function(ad) {
observer.observe(ad);
});
googletag.pubads().enableSingleRequest();
googletag.pubads().collapseEmptyDivs();
googletag.enableServices();
// Trigger lazy loading on scroll
window.addEventListener('scroll', lazyLoadAds);
window.addEventListener('resize', lazyLoadAds);Editor is loading...
Leave a Comment