30

Some websites have lots of images, so lazyloading seems appropiate to reduce load times and data consumption. But what if you also need to support printing for that website?

I mean, you can try to detect the print event and then load the images, with something like this:

HTML

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">

Note: this is a one by one pixels gif dummy image.

JavaScript

window.addEventListener('DOMContentLoaded', () => {
  img = document.querySelector('img');
  var isPrinting = window.matchMedia('print');
  isPrinting.addListener((media) => {
    if (media.matches) {
      img.src = 'http://unsplash.it/500/300/?image=705';
    }
  })
});

Note: if you try this in a code playground, remove the DOMContentLoaded event (or simply fork these: JSFiddle | Codepen).

Note: I didn't event bother with the onbeforeprint and onafterprint for obvious reasons.

This will work fine if the image is cached, but then again that's precisely not the point. The image/s should all load and then appear in the printing screen.

Do you have any ideas? Has anyone successfully implemented a print-ready lazyloading plugin?

Update

I've tried redirecting the user after the print dialog is detected, to a flagged version of the website a.k.a website.com?print=true where lazyloading is deactivated and all images load normally.

This method is improved by applying the window.print() method in this flagged print-ready version of the page, opening a new print dialog once all images are finished loading, and showing a "wait for it" message in the meantime at the top of the page.

Important note: this method was tested in Chrome, it does not work in Firefox nor Edge (hence why this is not an answer, but a testimony).

It works in Chrome beacuse the print dialog closes when you redirect to another website (in this case same url but flagged). In Edge and Firefox the print dialog is an actual window and it does not close it, making it pretty unusable.

6
  • 1
    have u tried stackoverflow.com/questions/15147907/… May 3, 2017 at 10:43
  • Hey! Can you please clarify the question? What exactly are you looking for? Lazy load images when user is about to print? Can you demonstrate the issue? May 3, 2017 at 17:12
  • 1
    @WearyAdventurer I'm looking for a way to load all images that weren't loaded because they're are waiting to be lazyload, as soon as the user opens the print dialog. The issue is demonstrated in any of the code playgrounds I have made available, just hit Ctrl + P with an empty cache.
    – undefined
    May 4, 2017 at 20:32
  • @IsmailFarooq Yes.
    – undefined
    May 4, 2017 at 20:33
  • That's a clever solution in your update; with your update, are you saying you're not able to call window.print() in Firefox nor Edge? Or unable to redirect? Or something else? Apologies, it's probably straight forward, I need some coffee! May 9, 2017 at 15:45

5 Answers 5

16
+100

Based on your desired functionality, I'm not quite sure what you want to do is feasible. As a developer we don't really have control over a users browser. Here are my thoughts as to why this isn't fully possible.

  1. Hooking the event to go and load your missing images won't let you guarantee images will make it from the server into your page. More specifically, the PDF generated for your print preview is going to get generated before your image(s) is done loading, the img.src = "..." is asynchronous. You'd run into similar issues with onbeforeprint as well, unfortunately. Sometimes it works, sometimes it does not (example, your fiddle worked when testing in safari, but did not in Chrome)

  2. You cannot stall or stop the print call -- you can't force the browser to wait for your image to finish loading in the lazy loading context. (I read something about using alerts to achieve this once, but it seemed really hacky to me, was more of a deterrent to printing than stalling)

  3. You cannot force img.src to get that data synchronously in a lazy-load context. There are some methods of doing this, but they are clever hacks -- referenced as pure evil and may not work in always. I found another link with a similar approach

So we have a problem, if the images are not loaded by the time print event is fired, we cannot force the browser to wait until they are done. Sure, we can hook and go get those images on print, but as above points out, we cannot wait for those resources to load before the print preview pops up.

Potential solution (inspired by links in point three as well as this link)

You could almost get away with doing a synchronous XMLHttpRequest. Syncrhonous XMLHTTPRequests will not let you change the responseType, they are always strings. However, you could convert the string value to an arrayBuffer encode it to a base-64 encoded string, and set the src to a dataURL (see the link that referenced clever hacks) -- however, when I tried this I got an error in the jsfiddle -- so it would be possible, if things were configured correctly, in theory. I'm hesitant to say yes you can, since I wasn't able to get the fiddle working with the following (but it's a route you could explore!).

var xhr = new XMLHttpRequest();
xhr.open("GET","http://unsplash.it/500/300/?image=705",false);
xhr.send(null);
if (request.status === 200) {
    //we cannot change the resposne type in synchronous XMLHTTPRequests
    //we can convert the string into a dataURL though
    var arr = new Uint8Array(this.response);
    // Convert the int array to a binary string
    // We have to use apply() as we are converting an *array*
    // and String.fromCharCode() takes one or more single values, not
    // an array.
    var raw = String.fromCharCode.apply(null,arr);

    // This is supported in modern browsers
    var b64=btoa(raw);
    var dataURL="data:image/jpeg;base64,"+b64;
    img.src = dataURL;
}

Work around to enhance the user experience

Something you could do is have some text that only displays in the print version of your page (via @print css media) that says "images are still loading, cancel your print request and try again" and when the images are finished loading, remove that "still waiting on resources try again message" from the DOM. Farther, you could wrap your main content inside an element that inverses the display to none when content is not loaded, so all you see is that message in the print preview dialog.

Going off of the code you posted this could look something like the following (see updated jsfiddle):

CSS

.printing-not-ready-message{
  display:none;
}
@media print{
  .printing-not-ready-message{
    display:block;
  }
  .do-not-print-content{
    display:none;
  }
}

HTML

<div class="printing-not-ready-message">
Images are still loading please cancel your preview and try again shortly.
</div>
<div class="do-not-print-content">
    <h1>Welcome to my Lazy Page</h1>
    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
    <p>Insert some comment about picture</p>
</div>

JavaScript

window.addEventListener('DOMContentLoaded', () => {
  img = document.querySelector('img');
  var isPrinting = window.matchMedia('print');
  isPrinting.addListener((media) => {
    if (media.matches) {
      img.src = 'http://unsplash.it/500/300/?image=705';
      //depending on how the lazy loading is done, the following might
      //exist in some other call, should happen after all images are loaded.
      //There is only 1 image in this example so this code can be called here.
      img.onload = ()=>{
          document.querySelector(".printing-not-ready-message").remove();
          document.querySelector(".do-not-print-content").className=""
      }
    }
  })
});
6
  • 3
    Very complete answer, if nobody else comes up with something, you'll have the bounty. In any case, +1.
    – undefined
    May 4, 2017 at 20:30
  • Thanks, this is a great question, have been thinking about nonstop since I first saw it. I got to thinking more about my point 3, I think it might be worth exploring, but I think jsFiddle was preventing the code from working (potentially a configuration on their end, or that of unsplash.it that stopped it from working). I updated my answer, the js in that is supported in modern browsers. If I find some more free time I'll play around with it some more! May 4, 2017 at 21:36
  • Interested to see if someone does think of something else! It's a neat problem to solve. May 4, 2017 at 21:49
  • 1
    Well, blocking the main thread with a synchronous http request is being deprecated, but maybe I can come up with something similar.
    – undefined
    May 6, 2017 at 3:25
  • That's a good point too, forgot that synchronous was being deprecated. May 9, 2017 at 1:21
3

I'm the author of the vanilla-lazyload script and I've recently developed a feature that makes print of all images possible!

Tested cross browser using this repo code which is live here.

Take a look and let me know what you think! I'm open to pull requests on GitHub of course.

3
  • 1
    I use your project everywhere! I'll try it out as soon as I can. When I was working on this issue the onbeforeprint event wasn't an option, but then again you do use matchMedia for Safari, so, I guess my question is, how did you get it to load all images before the print snapshot is taken.
    – undefined
    Oct 21, 2018 at 0:36
  • This doesn't work for me in FireFox. No images show in my print.
    – JohnPete22
    Aug 18, 2020 at 14:39
  • This is also broken on Chrome as of today and it requires to create a print button.
    – gerardnico
    Jun 12, 2021 at 6:42
1

I wrote a lazy loading jquery plugin that supports showing images on print using the window.onbeforeprint events and mediaQueryListeners. https://github.com/msigley/Unveil-EX/

1
//declare custom onbeforeprint method
const customOnBeforePrint = () => {
    const smoothScroll = (h) => {
        let i = h || 0;
        if (i < 200) {
            setTimeout(() => {
                window.scrollTo(window.scrollY, window.scrollY + i);
                smoothScroll(i + 10);
            }, 10);
        }
    };

    let height = document.body.scrollHeight;
    let newHeight;
    while (true) {
        smoothScroll(100);

        if (newHeight === height) break;
        height = newHeight;
    }
};

//override the onbeforeprint method
window.onbeforeprint = customOnBeforePrint;

Copy&Paste that block into devtool's console and then try to click print button. That workaround is working for me.

0

For whoever is in the same boat as I was: when using the browser native loading="lazy", you can simply remove that attribute when printing is going to happen. Below is my jQuery implementation.

window.onbeforeprint = function () {
  $('img').each(function () {
    $(this).removeAttr('loading')
  });
}

Chrome will then just load all images and they will show up when printing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.