image.onload event and browser cache
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
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();
});
There are two possible solutions for these kind of situations:
- Use the solution suggested on this post
-
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