【JS】jQueryを使って簡単にLoading画面をつくる
要所のみ。
JSでimgタグの数を拾ってきて、一つずつ読み込む。
読み込んだらそれをProgressBarのWidthとして吐き出していく。
ProgressBarのCSSは適当に色をつけておけば、画像をすべて読み込み終わった時点でLoadingが消える。
HTML
<div id="loading"> <div class="logo"> <img src="img/loading.png"> <div class="bar"> <span></span> </div> </div> </div>
/* * ■コンストラクタ関数(オブジェクトの初期化) */ function Loading(el) { this.initialize(el); } /* * ■初期化処理 */ Loading.prototype.initialize = function(el) { this.$el = el; this.$window = $(window); this.$document = $(document); this.handleEvents(); } /* * ■イベント検知 */ Loading.prototype.handleEvents = function () { var self = this; // ページ読み込み時 this.$document.on('ready', function (e) { var count = 0; var num = $('img').length; $('img').each(function() { var src = '<img src="' + $(this).attr('src') + '">'; $(src).one('load', function(){ count++; }).load(); }); var timer = setInterval(function() { $('#loading .bar span').css({'width': (count / num) * 100 + '%'}); if ((count / num) * 100 == 100) { clearInterval(timer); $('#loading').delay(800).fadeOut().queue(function() { $('#main').fadeIn(); }); } }, 5); }); } /* * ■js実行 */ var loading = new Loading ();