Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lazy load images and make them available for print

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.

like image 332
undefined Avatar asked Apr 30 '17 14:04

undefined


People also ask

How do you lazy load images?

Lazy Loading Techniques for images. Images on a webpage can be loaded in two ways - using the <img> tag, or using the CSS `background` property.

Should you lazy load images?

You should always use lazy loading for the images below the fold. As we explained, lazy loading will reduce the real and perceived loading time. User experience will benefit from it — and you users will thank you.

How do you lazy load?

To lazy load an image, display a lightweight placeholder image, and replace with the real full-size image on scroll. There are several technical approaches to lazy loading images: Inline <img> tags, using JavaScript to populate the tag if image is in viewport. Event handlers such as scroll or resize.


2 Answers

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=""       }     }   }) }); 
like image 129
Arthur Weborg Avatar answered Sep 30 '22 18:09

Arthur Weborg


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.

like image 22
verlok Avatar answered Sep 30 '22 18:09

verlok