javascriptimageeventsloadingloaded

How to check if an image is loaded if src was added later in the js code?


I have this dynamic code

dynamicBg.src = Dynamic_Content.Image_URL.Url; 
headline1.innerHTML = Dynamic_Content.Headline; 
headline2.innerHTML = Dynamic_Content.Headline2; 
headline3.innerHTML = Dynamic_Content.Headline3; 
fullHeadline.innerHTML = Dynamic_Content.fullHeadline;  
cta_1.innerHTML = Dynamic_Content.CTA;

So animation starts and the image appears later. Any ideas on how to check if the image is loaded and then animate?

thanx!

I tried with a timer but I want to catch the event exactly


Solution

  • You can and should use the load event of the image. Attach the handler first, then update the src attribute.

    var img = document.querySelector("img")
    img.addEventListener("load", function(ev) {
      console.log("image loaded")
    })
    img.src = "https://picsum.photos/150"
    <img>