I have written this page (using DataTables, PHP and Bootstrap 5.3). As you can see, in each row of the table I placed a button which triggers a modal, containing a responsive image (all the images are contained in the same folder). Everything works fine.
When I load the page, it takes a minute or so to finish loading and if I click on a button before it has finished loading, the modal dialog does not show the image. I suspect that all the images (about 30) are loaded when the webpage is opened.
If it is so, is there a way to prevent this? I guess it would be better to load each single image only when the corresponding button is clicked upon.
FYI – it’s better to include a code snippet in your question that demonstrates your problem rather than linking to your website. If your URL changes, there will not be any way for people who might have a similar problem to see what you were experiencing.
To delay loading images until if and when they’re needed, you can use the loading attribute set to lazy
.
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<table>
<tr>
<th>immagine</th>
</tr>
<tr>
<td>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
immagine
</button>
</td>
</tr>
</table>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<img src="https://placehold.co/600x400/webp" class="img-fluid" loading="lazy" width="600" height="400" alt="placeholder">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
One update – put your modal code after the table. A div
is not allowed as part of a table cell.
To speed up the image downloading time, resize the images to the display size (image 14_malga-bes-baldo.jpg could be reduced from 4333x3071 to 466x330) and use a newer format such as AVIF or WebP. If you'll be using different image sizes on different displays, then you could use srcset
to define different images for use on different displays. That give you more control rather than depending on the browser to shrink the image, and it saves on download time.