Reputation: 342
Using PHP I have written code to display images on the server to the website.
<div class="gallery">
<?php foreach (scandir("assets/images/gallery/") as $key => $value) { ?>
<?php if (preg_match('/[\s\S]+\.(png|jpg|jpeg)/', $value)) { ?>
<div class="grid-img">
<a href='assets/images/gallery/<?= $value ?>' rel="rel1" class="big">
<img class="grid-item_img" rel="rel1" src='assets/images/gallery/<?= $value ?>'>
</a>
</div>
<?php } ?>
<?php } ?>
</div>
This code does a scan in the assets/images/gallery/
directory and if a picture format is matched png, jpg or jpeg
the image is displayed in the gallery.
Now my problem is not with the code itself, it actually works and has no errors, but I feel like this isn't a very efficient approach to display images. If I have 100+ images on the server then all of them are loaded at the same time, causing a slow website.
How can I improve this code to be more viable on the website, so that a user doesn't get an unresponsive website because 100+ images are loading on the site? Is there a much more efficient way to do this?
The only solution I have is to maybe have the images hosted on an image hosting site, but I don't want these images to be hosted on a third-party website, because I want the admin to upload images to the server and have control over them.
Any tips are appreciated, thanks in advance.
Upvotes: 0
Views: 876
Reputation: 124
For the question
How can I improve this code to be more viable on the website, so that a user doesn't get an unresponsive website because 100+ images are loading on the site? Is there a much more efficient way to do this?
it's not possible to increase the visitor's download speed but bullets above help to decrease total duration to complete the page download.
Upvotes: 0
Reputation: 15070
You could use glob() instead to only select the files that match the pattern:
<?php foreach (glob("assets/images/gallery/*.{png,jpg,jpeg}", GLOB_BRACE) as $filename) { ?>
<div class="grid-img">
<a href='<?php echo $filename ?>' rel="rel1" class="big">
<img class="grid-item_img" rel="rel1" src='<?php echo $filename ?>'>
</a>
</div>
<?php } ?>
This does not help the client download faster. For that you could try preloading the images, or a higher upload speed using a fileserver e.g. Amazon S3.
Upvotes: 1