0

I'm using infinite scroll on my blog home page. I used Observer to insert Adsense ad when new element is added to DOM. Problem is push({}) is reloading all ad units when its exacted. The behavior am expecting is to refresh empty ad unit only

var totalLodedPosts = document.querySelectorAll('.post');
startcount = 24;
const observer = new MutationObserver(function(mutations_list) {
    mutations_list.forEach(function(mutation) {
        mutation.addedNodes.forEach(function(added_node) {
            if (added_node.classList.contains('post')) {
                totalLodedPosts = document.querySelectorAll('.post').length;
                if ((totalLodedPosts - startcount) == 24) {
                    startcount += 24
                    document.querySelector('.posts-wrap').innerHTML += ('<div class="item"><ins class="adsbygoogle" style="display:block"  data-ad-format="fluid" data-ad-layout-key="XXXXXXXXXX" data-ad-client="ca-pub-2XXXXXXXXXXXXXX9" data-ad-slot="XXXXXXXXXX"></ins></div>');
                    (adsbygoogle = window.adsbygoogle || []).push({});
                }
            }
        });
    });
});
  • 1
    Try using `insertAdjacentHTML()` instead of concatenating to `innerHTML`. See https://stackoverflow.com/questions/6304453/javascript-append-html-to-container-element-without-innerhtml – Barmar Mar 29 '23 at 20:40
  • 1
    I doubt it has anything to do with `push()`, it's the line before that's the problem. – Barmar Mar 29 '23 at 20:41

0 Answers0