[JavaScript] imagesLoaded – 画像のロードが完了したことを検知する

ページ上に配置される画像がすべてロードされてから実行したい処理がある場合に役立つスクリプト。

ImagesLoaded
http://imagesloaded.desandro.com/

ある案件で「ページに任意サイズの画像をグリッド状に配置して下端にフッタを表示する」というデザインがあって、フッタの位置はロードされた画像の高さを積算して求めないといけないので、すべての画像がロードされるのを待ってから計算処理する必要あり。最初はjQueryでloadイベントをフックしてみたんだけど、挙動が信用できないっぽかったので他の方法を探したところ、このスクリプトのお世話になって無事に実装を完了できたというわけ。

ちなみに、画像のロードの検知に関してはjQuery公式サイトにも注意事項が記載されている。

.load() | jQuery API Documentation
http://api.jquery.com/load-event/

Caveats of the load event when used with images

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

– It doesn’t work consistently nor reliably cross-browser
– It doesn’t fire correctly in WebKit if the image src is set to the same src as before
– It doesn’t correctly bubble up the DOM tree
– Can cease to fire for images that already live in the browser’s cache