0

I have the following code:

<?php
    $dir_handle = 'assets/splashs/';
    foreach(array_diff(scandir($dir_handle), array('.', '..')) as $file) {
        echo '<img id="preload_header" src="assets/splashs/' . $file . '" /><br />';
    }
?>

I wondered if it were possible to check if the image is successfully loaded, if so then remove the image and move onto the next?

My splashs folder has over 600 images in it, I don't want 600 images just sitting around on the side, but i'd like them to be preloaded for when I call them elsewhere.

load image => successfully loaded => remove and onto next image
           => unsuccessfully loaded => remove image and stop

Thanks for any help in advance.

user3352340
  • 145
  • 2
  • 11

1 Answers1

2

This is how you preload images:

<script type="text/javascript">
if (document.images) {
    img1 = new Image();
    img1.src = "image.jpg";
}
</script>

So you don't load AND SHOW the image (<img src="....">) but you load them into the browser using JavaScript so you don't have to "remove the images" afterwards because they'll never get shown.

Can be combined ofc with foreach:

<script type="text/javascript">
if (document.images) {
    <?php
    $i = 0;
    foreach(array_diff(scandir($dir_handle), array('.', '..')) as $file) {
        echo 'img' . $i . ' = new Image();' . PHP_EOL;
        echo 'img' . $i . '.src = "' . $file . '";' . PHP_EOL;
        $i++;
    }
    ?>
}
</script>
Daniel W.
  • 31,164
  • 13
  • 93
  • 151
  • Doesn't that mean that I'd have to put in a src for every image? Would it be possible to do a `foreach()` to find the names of the images in the folder and replace the `.src` with their location? – user3352340 Mar 04 '14 at 11:38
  • @user3352340 you can use foreach, ofc to generate the JS. – Daniel W. Mar 04 '14 at 12:17