washingtonpost / ArcAds

ArcAds is a DFP wrapper created by Arc XP with publishers in mind.
https://www.npmjs.com/package/arcads
MIT License
56 stars 42 forks source link

Lazyloading? #39

Open jonathanstegall opened 5 years ago

jonathanstegall commented 5 years ago

Expected Behavior

I'm hoping to learn if you've thought about incorporating lazy loading into this library. Perhaps with IntersectionObserver?

Actual Behavior

Currently all of the ads load when the page loads.

jonathanstegall commented 5 years ago

Well here's one way of doing this that I've been testing.

In the head of my document:

<script src='arcads.js'></script>
<script>
const arcAds = new ArcAds({
    dfp: {
        id: 'myid'
    }
});
</script>
<script>
    window.addLazyLoad = function(ad) {
        return new Promise(function(resolve, reject) {
            var this_ad_id = ad.adId;

            function handler( entries, observer ) {
              for ( entry of entries ) {
                if ( entry.isIntersecting ) {
                  resolve();
                }
              }
            }

            let observer = new IntersectionObserver( handler );
            observer.observe( document.getElementById( this_ad_id ) );

        });
    }           
</script>

Then in the place where the ad needs to display:

<div id="acm-ad-tag-x100"></div>
<script>
    arcAds.registerAd({
        id: 'acm-ad-tag-x100',
        slotName: 'dfp_default',
        dimensions: [[300,250]],
        prerender: window.addLazyLoad,
    });
</script>

I've just started testing, but so far this appears to work (either in browsers that already support IntersectionObserver or with a polyfill). I need to investigate more so I can make sure it begins to load a few pixels before the ad is in view, and maybe some other things, but this appears to be a good start and would require no additions to this library at all, unless you'd want to document it.

pm-harshad-mane commented 3 years ago

Hello @jonathanstegall almost 2 years after your post :) does it work?

jonathanstegall commented 3 years ago

@pm-harshad-mane yes, I think this ended up being what we use. I ultimately made a WordPress plugin that uses this library.

loxator commented 3 years ago

@jonathanstegall Thank you for this! I didn't know something like IntersectionObserver existed, and it also helped me solve the LazyLoading issue!