Search code examples
javascriptimage-loading

image.onload event and browser cache


I want to create an alert box after an image is loaded, but if the image is saved in the browser cache, the .onload event will not be fired.

How do I trigger an alert when an image has been loaded regardless of whether the image has been cached or not?

var img = new Image();
img.src = "img.jpg";
img.onload = function () {
   alert("image is loaded");
}

Solution

  • As you're generating the image dynamically, set the onload property before the src.

    var img = new Image();
    img.onload = function () {
       alert("image is loaded");
    }
    img.src = "img.jpg";
    

    Fiddle - tested on latest Firefox and Chrome releases.

    You can also use the answer in this post, which I adapted for a single dynamically generated image:

    var img = new Image();
    // 'load' event
    $(img).on('load', function() {
      alert("image is loaded");
    });
    img.src = "img.jpg";
    

    Fiddle