13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

画像プリロード(要jQuery)

Posted at

jQueryを使った画像のプリロード。
ファイルパスを配列で渡せばプリロードしてくれる。
とりあえず開始、プログレス、完了時の関数指定は必須。
一応、ロード中の状況をパーセンテージで返してくれるけど、ファイル数に対するパーセントなので全然正確じゃない。

JavaScript

/**
 *	画像のプリロード
 *	※)要jQuery
 *	
 *	@param	imageArray	画像パスの配列
 *	@param	startFnc	開始時に呼ばれる関数
 *	@param	progressFnc	ロード中に呼ばれる関数(パーセントが帰ってくる)
 *	@param	completeFnc	完了時に呼ばれる関数
 *
 */
function preloadImage(imageArray, startFnc, progressFnc, completeFnc){	
	function preload(images, progress){
		var total = images.length;
		$(images).each(function(){
			var src = this;
			$('<img/>').attr('src', src).load(function() {
				for(var i = 0; i < images.length; i++){
					if (images[i] == src) images.splice(i, 1);
				}
				progress(total, total - images.length);
			});
		});
	}
	
	var nowPercent = 0;
	startFnc();
	preload(imageArray, function(total, loaded){
		nowPercent = Math.ceil(100 * loaded / total);
		progressFnc(nowPercent);
		if(nowPercent >= 100){
			completeFnc();
		}
	});
}


// テストコード
$(function(){
	function start(){ console.log('start') }
	function progress(per){ console.log(per) }
	function complete(){ console.log('complete') }
	
	var images = [
		'img1.jpg',
		'img2.jpg',
		'img3.jpg',
		'img4.jpg',
		'img5.jpg',
		'img6.jpg',
		'img7.jpg',
		'img8.jpg',
		'img9.jpg',
		'img10.jpg'
	];
	
	preloadImage(images, start, progress, complete);
});

13
13
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
13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?