155

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");
}
1

6 Answers 6

209

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

14
  • Wait. Why does your second code example do the wrong thing and set .src before setting .onload? You had it right in the first code example, but messed up the second one. The second one will not work properly in some versions of IE.
    – jfriend00
    Commented Sep 10, 2012 at 16:42
  • 1
    @jfriend00 Nope, not a mess up. The back up code (2nd one) is exactly for in case the first one somehow stops working. =] It utilizes a .complete check in case the image was already cached, hence the code was demonstrating it. Of course, for the best practice, you can always set the src after all handlers binding. Commented Sep 10, 2012 at 17:21
  • 4
    There's just NO reason to rely on .complete in this case. Just set your load handler first before setting .src and it is NEVER needed. I've written a slideshow that is used by thousands of sites in every conceivable browser and the first technique works every time. There is no need to ever check .complete when create a new image from scratch like this.
    – jfriend00
    Commented Sep 10, 2012 at 17:24
  • Alright, thanks for the heads up, updated the answer to reflect your reasoning =]. Also @jfriend00 could you check if the image loads in IE? Wondering if it's an issue with my network or with IE and the image. Commented Sep 10, 2012 at 17:29
  • 9
    Also today I found that webkit needs img.src = '' before assigning new src if it was used before.
    – quux
    Commented May 24, 2014 at 10:53
15

If the src is already set then the event is firing in the cached case before you even get the event handler bound. So, you should trigger the event based off .complete also.

code sample:

$("img").one("load", function() {
   //do stuff
}).each(function() {
   if(this.complete || /*for IE 10-*/ $(this).height() > 0)
     $(this).load();
});
6

There are two possible solutions for these kind of situations:

  1. Use the solution suggested on this post
  2. Add a unique suffix to the image src to force browser downloading it again, like this:

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

In this code every time adding current timestamp to the end of the image URL you make it unique and browser will download the image again

5
  • 63
    All this does is defeat caching. It is the WRONG way to solve this problem. The right way is in Fabricio's answer. Just set the .onload handler before setting the .src value and you won't miss the onload event in some versions of IE.
    – jfriend00
    Commented Sep 10, 2012 at 16:41
  • 2
    yes you are right, but it is not always desirable to cache, sometimes images should not be cached. of course in this particular situation it depends on the needs
    – haynar
    Commented Sep 10, 2012 at 18:19
  • 1
    In my angular app I tried everything that other answers says, but didn't help. But forcing not to cache like this answer says did work for me. So plus one from me.
    – Thanu
    Commented Jan 6, 2016 at 0:21
  • The only solution that worked for me in latest version Chrome.
    – Young Bob
    Commented Feb 28, 2018 at 18:24
  • Fixed my problem when the picture has the same name, but in fact changed Commented Jun 5, 2023 at 7:27
3

I have met the same issue today. After trying various method, I realize that just put the code of sizing inside $(window).load(function() {}) instead of document.ready would solve part of issue (if you are not ajaxing the page).

2
  • This is also a good answer for the situation where browser has image cached, works ok with window load Commented Feb 25, 2016 at 18:25
  • exactly the issue I was facing. changing $(document).ready to $(window).load solved my problem. Commented Jun 29, 2020 at 13:52
2

My improvement:

document.addEventListener("DOMContentLoaded", function () {
  let el = document.getElementsByTagName("img")
  Object.values(el).forEach(function (el) {
    var img = new Image();
    img.onload = function () {
      el.style.opacity = 1;
    }
    img.src = el.src
  })
});

.

<style>
  img {
    opacity: 0;
    transition: opacity .4s cubic-bezier(.25, .45, .45, .95);
  }
</style>
1
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Apr 12, 2023 at 13:46
-2

I found that you can just do this in Chrome:

  $('.onload-fadein').each(function (k, v) {
    v.onload = function () {
        $(this).animate({opacity: 1}, 2000);
    };
    v.src = v.src;
});

Setting the .src to itself will trigger the onload event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.