Skip to content

Commit

Permalink
Properly support tracking existing <img> tags
Browse files Browse the repository at this point in the history
The cache mechanism would interfere before
  • Loading branch information
bfred-it committed Oct 3, 2016
1 parent 4bb4a00 commit 2e420bc
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 34 deletions.
2 changes: 1 addition & 1 deletion dist/image-promise.browser.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

67 changes: 34 additions & 33 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,50 +1,51 @@
'use strict';
function trackLoading(image, src) {
if (src) {
image.src = src;
}
const promise = new Promise((resolve, reject) => {
if (image.complete) {
resolve(image);
} else {
image.addEventListener('load', () => resolve(image));
image.addEventListener('error', () => reject(image));
}
});
promise.image = image;
return promise;
}

export default function load(src) {
export default function load(image) {
// if argument is an array, treat as
// load(['1.jpg', '2.jpg'])
if (src.map) {
return Promise.all(src.map(load));
if (image.map) {
return Promise.all(image.map(load));
}

// check whether an <img> was passed as argument
let image = new Image();
if (src.src) {
image = src;
src = src.src;
// if image is just a <img>, don't cache it
if (image.src) {
return trackLoading(image);
}

if (!load[src]) {
load[src] = new Promise((resolve, reject) => {
image.addEventListener('load', () => resolve(image));
image.addEventListener('error', () => reject(image));

if (!image.src) {
image.src = src;
}

if (image.complete) {
resolve(image);
}
});
load[src].image = image;
// load is treated as a map, assumes all image paths don't clash with Function.prototype
if (!load[image]) {
load[image] = trackLoading(new Image(), image);
}
return load[src];
return load[image];
}

load.unload = function (src) {
// an <img> was passed as argument
if (src.src) {
src = src.src;
load.unload = function (image) {
if (!image.src) {
// an <img> was passed as argument, so nothing to unload
return;
}

// if argument is an array, treat as
// load(['1.jpg', '2.jpg'])
if (src.map) {
src.map(load.unload);
} else if (load[src]) {
if (image.map) {
image.map(load.unload);
} else if (load[image]) {
// GC, http://www.fngtps.com/2010/mobile-safari-image-resource-limit-workaround/
load[src].image.src = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
delete load[src];
load[image].image.src = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
delete load[image];
}
};

0 comments on commit 2e420bc

Please sign in to comment.