skip to Main Content

How to wait for a file (eg. "sunny.png") and send an alert, when it’s loaded using JavaScript.

network tab example

My original intention was to just wait for the whole page to load, but DOMContentLoaded and document.readyState were all very early, with window.onload the page was still loaded and the event didn’t fire. I have to wait for the last file to load. I don’t have access to edit the original page.

2

Answers


  1. You can use the Image object in JavaScript to load an image and then use the onload event to trigger an alert when the image is fully loaded. Here’s an example:

    const img = new Image();
    img.src = 'sunny.png';
    
    img.onload = function() {
      alert('Image loaded!');
    };
    

    In this example, img.onload is a function that will be called when the image is fully loaded. The alert function will then display an alert message saying "Image loaded!".

    Login or Signup to reply.
  2. You can simply use onload function to check this.

    function imageLoaded() {
      console.log("Image loaded");
    }
    <img id="myimage" onload="imageLoaded()" src="https://t3.ftcdn.net/jpg/05/69/37/42/360_F_569374252_MibZowvlZC0fYV3eGCD9sXL9AYDlvKfd.jpg">

    Onload in HTML,

    <element onload="myScript">
    

    In JavaScript:

    object.onload = function(){myScript};
    

    In JavaScript, using the addEventListener() method:

    object.addEventListener("load", myScript);
    

    For more reference: mdn,w3school

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search