Reputation: 1609
I have a background image and lots of product image. Shortly, %88 of entire page is image. But when i refresh the page. Some products are displaying. After that my background is coming. Then other divs, images are coming.
What i want to do is my background images comes first. Then others are must be displayed. Sync or async it is not important.
What i tried: i replaced my background image div to the top of the dom. Not worked.
window.onload=function () {
document.getElementById("theBackgroundImage").style.visibility = "visible";
}
Not worked also.
I tried several things before. But i have still same issue.
Upvotes: 2
Views: 398
Reputation: 2220
First of all, you will need to detect when all your images are loaded. Or preferably when all the images you want displayed first.
Then i see two options here. For both, i'm going to use a library that helps in detecting when images have been loaded : https://imagesloaded.desandro.com/
1st option
Just display your image.
imagesLoaded( 'img', function() {
document.querySelectorAll(".displayAfter").forEach(e => e.style.visibility = 'visible'
)
});
.displayAfter {
visibility : hidden;
}
<script src="https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.min.js"></script>
Image here :
<img width="50px" height="50px" src="https://picsum.photos/50/50?random" />
Lazy loaded image here :
<img class="displayAfter" width="50px" height="50px" src="https://picsum.photos/50/50" />
2nd option
Do not load your image first (for instance src empty or pointing to blank image) then change the src attribute of your image. Here i use a data-src
attribute in the image that i simply insert into the image src
attribute once all the other images are loaded.
imagesLoaded( 'img', function() {
document.querySelectorAll(".displayAfter").forEach(e =>
e.setAttribute('src', e.getAttribute('data-src'))
)
});
<script src="https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.min.js"></script>
Image here :
<img width="50px" height="50px" src="https://picsum.photos/50/50?random" />
Lazy loaded image here :
<img class="displayAfter" data-src="https://picsum.photos/50/50" width="50px" height="50px" />
Upvotes: 1