How to load images into a page using a php file but wait for all images load before displaying

  php

This is the minimum code in order to demonstrate the effect.

https://replit.com/@computinginschools/imageload#index.php

This is a simple php file which loads image using an external script, image.php, and displays them on the page. The reason I have done this on my live site is because the images are stored outside the www folder and I need the image.php script to access them. To make it easier I have just put everything under the webroot.

In this example, all the images are located in a folder called images next to index.php.

<html>
  <head>
    <title>Image Load</title>
  </head>
  <body>
    <?php 
      $images = glob('images/*.png');
      foreach($images as $image){
        echo('<img src="image.php?i='.urlencode($image).'" loading="lazy">');
      }
    ?> 
  </body>
</html>

This is the image.php file which loads the images.

<?php
  $path = urldecode($_GET['i']);

  if (file_exists($path)) {
    $extension = pathinfo($path)['extension'];
      header('Content-type:'.$extension);
      header('Cache-control:public, max-age=604800');
      header('Accept-ranges:bytes');
      header('Content-length:'.filesize($path));
      header('Last-Modified: '.date(DATE_RFC2822, filemtime($path)));
      header_remove('pragma');
      echo(file_get_contents($path));
  }
  else {
    echo("File not found: ".$file);
  }
?>

The script works fine to display the images however, the loading is often prolonged with all the images loading in a ‘wave’ as the image.php file renders them on the screen after index.php has loaded. The REPL is fast so this is not really noticeable, however, on my production site, this effect is quite pronounced.

I would like to know if there is a way of delaying the loading of the images in index.php until all the images rendered by images.php have loaded. My intention is to set the display attribute of the images to none by default and then, when the index.php document has loaded, apply an appear animation to all the images on the page to make them fade into view.

It would be even better if I could embed some kind of loading animation in the container for each image.

Please help?

Source: Ask PHP

LEAVE A COMMENT