본문 바로가기

javascript

image onload


I want after load image, alert some, but here is 1 problem: as I know, if img is saved in browser cache,img.onload event will be not called. So, how solve this problem, how make alert after every refresh document, despite img saved in browser cache or not, tell please someone.

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

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


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









I want to do:

$("img").bind('load', function() {
  // do stuff
});

But the load event doesn't fire when the image is loaded from cache. The jQuery docs suggest a plugin to fix this, but it doesn't workactive

If the src is already set, then the event is firing in the cached case, before you even get the event handler bound. To fix this, you can loop through checking and triggering the event based off .complete, like this:

$("img").one("load", function() {
  // do stuff
}).each(function() {
  if(this.complete) $(this).load();
});

Note the change from .bind() to .one() so the event handler doesn't run twice.

shareimprove this answer


'javascript' 카테고리의 다른 글

자바스크립트 상속!! 후......ㅠ  (0) 2016.07.21
apply call  (0) 2016.07.21
apply, call 상속하기  (0) 2016.07.18
클로저의 힘을 느껴보자!!  (0) 2016.07.18
간단한 호이스팅 설명  (0) 2016.07.18