Search code examples
javascriptimageonloadloader

How to show loader overlay until image is loaded on webpage?


I want to make a loading overlay, but instead using setTimeout I would like to show the "loader" until the first image is fully loaded on the webpage. ( After that, I would like to use lazy image loading )

Until now I used setTimeout, but it's not working really well. I can set a bigger time, but now there is a "gap" between the loader and when the image appears.

The picture urls are fetched from a wordpress API and I'm using template. What I want is to show the "loading" overlay until the first image is fully loaded, so users don't see the blank state.

var img = document.querySelector("#img");

img.onload = function(){ 
  document.getElementById("loading").style.display = "none" 
}   

I can't use jQuery because it's for a school project. I tried all the alternatives I found here by adding a console.log("loaded") when it's loaded, but nothing seems to work.


Solution

  • Maybe set the img.src after you defined onload

    let img = document.createElement('img');
    img.onload = function(){}
    img.src = "url"