Load google ad each time infinite scroll loaded

34 Views Asked by At

I have implented Infinite scroll jQuery on my wordpress website. I want to load my google Ads (in sidebar) each time when content loaded. But I am getting All ins elements in the DOM with class=adsbygoogle already have ads in them.

I tried to place (adsbygoogle = window.adsbygoogle || []).push({}); in each scroll access but it is not working. Is there any way to make this work? Any help would be much appreciated. Thank you!

    let ias = new InfiniteAjaxScroll('.single-post-ias', {
        logger: false,
        item: '.load_more_ias_single',
        next: '.nav-previous a',
        spinner: '.loader'
    });

    ias.on('load', function () {
        let uri = extractLastSegment(this.container.baseURI);
        loadSidebarAds(uri);
    });

    ias.on('loaded', function () {

        $('.loader').css('display', 'none');
        $(".toc-list").hide();

        $(".table_heading").click(function () {
            $(".toc-list").slideToggle("slow");
        });
        $("a[href^=\'#\']").click(function (event) {
            event.preventDefault();
            var target = $(this.hash);
            $("html, body").animate({
                scrollTop: target.offset().top
            }, 1000);
        });
    });
    ias.on('rendered', function (items) {
        console.log(this);
    });
    ias.on('appended', function () {
        $(".toc-list").hide();

        $(".table_heading").click(function () {
            $(".toc-list").slideToggle("slow");
        });
        $("a[href^=\'#\']").click(function (event) {
            event.preventDefault();
            var target = $(this.hash);
            $("html, body").animate({
                scrollTop: target.offset().top
            }, 1000);
        });
    })
    ias.on('page', (e) => {
        document.title = e.title;

        let state = history.state;

        history.replaceState(state, e.title, e.url);
    });

    ias.on('load', function (event) {
        event.nocache = true;
    });


function loadSidebarAds(uri) {
    
    var adIns = document.createElement("ins");
    adIns.className = "adsbygoogle";
    adIns.style.display = "block";
    adIns.setAttribute("data-ad-client", "ca-pub-id");  
    var targetingSlug = uri; 
    adIns.setAttribute("data-ad-slot", "slot-" + targetingSlug);
    $(".custom-html-widget").append(adIns);
    (adsbygoogle = window.adsbygoogle || []).push({});
}



function extractLastSegment(uri) {
    uri = uri.replace(/\/$/, '');
    var segments = uri.split('/');
    var lastSegment = segments[segments.length - 1];
    return lastSegment;
}

Is there anything I am doing wrong here?

0

There are 0 best solutions below