Skip to content

Instantly share code, notes, and snippets.

@steveluscher
Forked from eikes/imgpreload.js
Last active August 29, 2015 14:24
Show Gist options
  • Save steveluscher/847ff44423b71a1d2eae to your computer and use it in GitHub Desktop.
Save steveluscher/847ff44423b71a1d2eae to your computer and use it in GitHub Desktop.
/*
* Copyright (C) 2012 Eike Send
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
function preloadImages(imgUrls, callback) {
"use strict";
var images = [];
var numLoaded = 0;
imgUrls = Object.prototype.toString.call(imgUrls) === '[object Array]'
? imgUrls
: [imgUrls];
var handleLoad = function() {
numLoaded++;
// Some browsers fire onload events whenever an animated
// GIF restarts a loop, so remove the on* handlers now.
this.onabort = this.onerror = this.onload = null;
if (callback && numLoaded === imgUrls.length) {
callback(images);
}
};
var image;
for (var i = 0; i < imgUrls.length; i++) {
image = images[i] = new Image();
image.onabort = image.onerror = image.onload = handleLoad;
image.src = imgUrls[i];
if (image.complete) {
// Image is likely cached. Fire the handler right away.
image.onabort = image.onerror = image.onload = null;
handleLoad.call(image);
}
}
}
@steveluscher
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment