この記事は 約 0分56秒 で読めます。
★jqueryを用いたプリローダー
画像単体の読み込みではなく、複数の画像の読み込み時に使用することを想定しています。
画像読み込み完了をきっかけに処理を行うものなので、画像単体の純粋な読み込み処理(1000byte中598byte読み込んでいますとか)ではありません。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
var nowPercent = {}; function preload(images, preloader, initialize, progress, complete){ var img = []; var total = images.length; var decrementCount = total; nowPercent[preloader] = 0; $(images).each(function(i){ var src = this; img[i] = new Image(); img[i].onload = function(){ decrementCount--; nowPercent[preloader] = Math.ceil(100 * (total - decrementCount) / total); if(decrementCount === total - 1){ //initialize initialize(); } if(0 < decrementCount){ //progress progress(); } else{ //complete complete(); } }; img[i].src = src; }); } function removeWithKey(target, keyName) { for(var key in target){ if(key === keyName){ delete target[key]; } } } |
★使用例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
var allImages = []; $('html').find('img').each(function(){ allImages.push($(this).attr('src')); }); //または var allImages = [ "img/***.png", "img/***.png", "img/***.png" ]; //基本 preload(allImages, 'allImages', //name function(){ //initialize var displayingPercent = 0; var timer = window.setInterval(function() { if (displayingPercent >= 100) { //complete window.clearInterval(timer); removeWithKey(nowPercent, 'allImages'); } else { //progress if (displayingPercent < nowPercent['allImages']) { displayingPercent++; $(progressElement).css('width', displayingPercent + '%'); } } }, 15); }, function(){ //progress }, function(){ //complete } ); //低性能ブラウザ(IE8以前とか)or低性能デバイス preload(allImages, 'allImages', //name function(){ //initialize }, function(){ //progress $(progressElement).css('width', nowPercent['allImages'] + '%'); }, function(){ //complete removeWithKey(nowPercent, 'allImages'); } ); |
厳密な処理の話で言えば低性能ブラウザ向けの処理のほうが正しいものですが、画像が軽い場合、または画像がキャッシュされている場合、ローディング画面が一瞬で消えるので、タイマーでひとつずつ目盛りをあげていくような処理を初期化時に登録してそちらで完了処理もウォッチするような仕組みにしています。
読み込み完了したらパーセント表示用の「nowPercent 」から処理に使った該当変数を削除しています。メモリから変数を解放するという意図なんですが、これ効果あるのかよく調べていません。詳しい人教えて…