LoginSignup
3
4

More than 5 years have passed since last update.

IE9でimageのonloadが走らない問題を無理やり解消する

Posted at

IE9ではimageを読み込んだときにonloadが走らないという問題があります。
その他のブラウザでは、imageのsrcにキャッシュバスターをつけることで解決しますが、
IE9に関してはキャッシュバスターをつけても解決しません。

そこで、onload以外のプロパティを使ってonload的役割を無理やり実装しましょう。
imageにはwidth, heightというプロパティがあります。
そしてこれらのプロパティは、imageがまだ読み込まれてない段階では0という値を持っています。
読み込まれたとき、widthとheightにその画像の幅・高さがあてられます。

この値をsetIntervalで監視することで、画像が読み込まれたタイミングをとることができるという技です。

onload.js
var img = new Image();

setInterval(function(){
    if ( img.width > 0 ){
        alert( "image loaded." );
    }
}, 50);

img.src = "img/hoge.jpg"; 

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4