Robert Tossly Robert Tossly - 1 month ago 6
PHP Question

Most robust way to preload image to prevent visible image load? (Without JS)

I've just finished creating an image upload feature and am a little disappointed.

Whilst visiting a page that contains one or more photos, I am experiencing:


  • Tedious load time (~0.5 secs).

  • Unaesthetic image loading (You can see the photo load from top to bottom).



My question is: How can I make sure the entire photo is loaded before presenting it to the user (I am trying to figure out a way to make sure the
image
is fully loaded before the
body
) without using Javascript?

Note: This question is assuming the photo is being loading from a folder cache in the same directory..

Answer

1. Progressive JPEG

To avoid the "top to bottom" loading of an image you may use "progressive jpeg" which renders a "blurred" version of the picture during it's loading instead of "top to bottom" : Ex. : http://blog.patrickmeenan.com/2013/06/progressive-jpegs-ftw.html

2. Embedded (encoded in base64)

If you really want to show images and the page at the same time you should encode them as base64 and include them in your page :

<img src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." alt="" />

You can do it via PHP or any server side script.

<img src="data:image/jpeg;base64,<?=base64encode(file_get_contents($file_path))?>" alt="" />

https://en.wikipedia.org/wiki/Data_URI_scheme#Web_browser_support

3. Disguised as stylesheets (awful hack)

If you want to reaaaaally block rendering before images are loaded, you could double images in your page in a <link rel=stylesheet> tag in the <head> section of your page.

Browsers won't show the page until CSSs are loaded, even though your files are not CSS it will load and cache them, and once loaded the page will render and your images will be loaded from cache.

<html>
<head>
  <link rel="stylesheet" href="your_image_01.jpg" />
  <link rel="stylesheet" href="your_image_02.jpg" />
</head>
<body>
...
  <img src="your_image_01.jpg" alt="" />
  ...
  <img src="your_image_02.jpg" alt="" />
...
</body>
</html>