Last active
December 14, 2015 14:59
-
-
Save RyoSugimoto/5104985 to your computer and use it in GitHub Desktop.
指定した画像を読み込んでから、コールバック関数を実行する(画像の先読みを行なう)。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 指定した画像の読み込みがすべて終了してから | |
* コールバック関数を実行する。 | |
* @param options.src {string/array} 画像のソースの文字列または配列 | |
* @param options.complete {function} すべての画像の読み込みが完了するか失敗したときに、最後に実行する関数 | |
* @param options.success {function} 読み込みが完了するたびに実行する関数 | |
* @param options.error {function} 読み込みに失敗するたびに実行する関数 | |
* @param options.cache {bool} 画像のキャッシュを利用するかどうか | |
*/ | |
var preloadImages = function (options, i) { | |
var self = preloadImages; | |
var newImage = new Image(); | |
var isArray = false; | |
i = (typeof i === 'number') ? i : 0; | |
options.cache = options.cache !== false ? true : false; | |
newImage.onload = function () { | |
if (typeof options.success === 'function') { | |
options.success(i, newImage); | |
} | |
_next(); | |
} | |
newImage.onerror = function () { | |
if (typeof options.error === 'function') { | |
options.error(i, newImage); | |
} | |
_next(); | |
} | |
if (options.src instanceof Array) { | |
newImage.src = options.src[i] + (options.cache ? '' : '?' + new Date().getTime()); | |
isArray = true; | |
} else if (typeof options.src === 'string') { | |
newImage.src = options.src + (options.cache ? '' : '?' + new Date().getTime()); | |
} else { | |
_error(); | |
return false; | |
} | |
function _next () { | |
i++; | |
if (isArray && options.src.length > i) { | |
self(options, i); | |
} else if (typeof options.complete === 'function') { | |
options.complete(); | |
} | |
} | |
function _error () { | |
throw new Error('There is an invalid parameter.'); | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example | |
preloadImages({ | |
src: [ | |
'img/01.jpg', | |
1, | |
'img/03.jpg', | |
'img/04.jpg', | |
'img/05.jpg' | |
], | |
complete: function () { | |
console.log('complete!'); | |
}, | |
success: function (i, newImage) { | |
console.log(i + ': success!' + newImage.src); | |
document.body.appendChild(newImage); | |
}, | |
error: function (i, newImage) { | |
console.log(i + ': error!' + newImage.src); | |
}, | |
cache: false | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment