To display images on a webpage, I recommend using the <img>
element and then removing it once the image has loaded. By setting the image's src
as the background of its parent element, you can achieve this effect efficiently:
let pictureDivs = document.querySelectorAll('.picture img');
for (var i = 0; i < pictureDivs.length; i++) {
pictureDivs[i].addEventListener('load', pictureLoaded)
}
function pictureLoaded(e) {
let divElem = e.target.closest('div');
divElem.style.backgroundImage = 'url('+this.src+')';
divElem.classList.add('loaded');
divElem.removeChild(divElem.querySelector('img'));
}
.container{
overflow: hidden;
}
.picture {
background-size: cover;
width: 400px;
height: 400px;
transform: translatex(-100%);
overflow: hidden;
}
.picture.loaded{
animation: slideInFromLeft 1s cubic-bezier(.5,0,.3,1) forwards;
}
.picture img {
height: 0;
}
@keyframes slideInFromLeft {
0% {
transform: translatex(-100%);
}
100% {
transform: translatex(0);
}
}
<div class="container">
<div class="picture">
<img src="https://images.wallpaperscraft.com/image/honda_civic_type_r_honda_type_r_honda_129270_3840x2160.jpg">
</div>
</div>
This method triggers the animation for each individual <div>
containing an image as soon as that specific image loads, rather than waiting for all images on the page to load before animating (as with window.load
).
It is worth noting that while this technique optimizes image loading, it is important to ensure your website does not overload with heavy resources. Image optimization and proper sizing are key steps in optimizing website performance. Consider utilizing srcset for responsive images.