DEV Community

Raymond Camden
Raymond Camden

Posted on • Originally published at raymondcamden.com on

Load a PDF Embed when Visible

A quick tip before I turn my brain off for the weekend (that's not entirely true, tonight I plan on building LEGO). I've blogged before about the PDF Embed API, it's one of the tools my new job involves. If you didn't see my first post on it, definitely give it a quick read: Using the PDF Embed API with Vue.js Today's tip is a bit simpler - how can we use the PDF Embed API to only load a PDF once it's actually visible in the DOM?

Turns out it's rather simple. Modern browsers support the Intersection Observer API. When I say "modern browsers", I mean all but Safari, but they're working on it. You can find more details at CanIUse: https://caniuse.com/intersectionobserver.

I thought I'd do a quick demo of using the PDF Embed API and Intersection Observer together. Turns out it was incredibly simple:

const ADOBE_KEY = 'b9151e8d6a0b4d798e0f8d7950efea91';

if(!!window.IntersectionObserver) {
    const pdfBox = document.querySelector('#pdfArea');

    const intersectionObserver = new IntersectionObserver(function(entries, observer) {
        if(entries && entries[0] && entries[0].isIntersecting){
            loadPDF();
            observer.unobserve(pdfBox);
        }
    });
    intersectionObserver.observe(pdfBox);
} else loadPDF();

function loadPDF() {
    console.log('visible');
    const adobeDCView = new AdobeDC.View({
        clientId: ADOBE_KEY, 
        divId: "pdfArea"
    });
    adobeDCView.previewFile({
      content:{ 
                location: 
        { url: "https://documentcloud.adobe.com/view-sdk-demo/PDFs/Bodea%20Brochure.pdf" }
            },
      metaData:{ fileName: "Bodea Brochure.pdf"}
    },
    {
      embedMode: "SIZED_CONTAINER"
    });
}
Enter fullscreen mode Exit fullscreen mode

Basically, if the browser supports the API, I set up an observer to monitor part of the DOM (see the earlier querySelector. When it detects that it's visible, I run loadPDF. If the API is not supported, I just run loadPDF immediately.

And that's it. I freaking love how simple that was. If you want to see a demo with some lovely Cat Ipsum, take a gander at the CodePen below.

See the Pen PDF when Visible Test by Raymond Camden (@cfjedimaster) on CodePen.

Photo by Michael Dziedzic on Unsplash

Top comments (0)