Skip to content

Commit 98f2c6c

Browse files
author
Laurent Goudet
committed
Add start & load Promises
1 parent 0647aac commit 98f2c6c

File tree

1 file changed

+24
-19
lines changed

1 file changed

+24
-19
lines changed

lazyimage.js

+24-19
Original file line numberDiff line numberDiff line change
@@ -5,30 +5,35 @@
55
*/
66
exports.build = false;
77
exports.fetch = function(load) {
8-
load.metadata.imgPromise = new Promise(function(resolve, reject) {
9-
function loadImage() {
10-
var img = new Image();
11-
img.onload = function(evt) {
12-
try {
13-
delete img.onload; //release memory - suggested by John Hann
14-
} catch(err) {
15-
img.onload = function() {}; // IE7 :(
8+
load.metadata.start = new Promise(function(startResolve) {
9+
load.metadata.load = new Promise(function(loadResolve, loadReject) {
10+
function loadImage() {
11+
var img = new Image();
12+
img.onerror = loadReject;
13+
img.onload = function(evt) {
14+
try {
15+
delete img.onload; //release memory - suggested by John Hann
16+
} catch(err) {
17+
img.onload = function() {}; // IE7 :(
18+
}
19+
loadResolve();
1620
}
21+
img.src = load.address;
22+
startResolve(img);
23+
};
24+
if (document.readyState === 'complete') {
25+
loadImage();
26+
} else {
27+
window.addEventListener('load', loadImage, false);
1728
}
18-
img.src = load.address;
19-
resolve(img);
20-
};
21-
if (document.readyState === 'complete') {
22-
loadImage();
23-
} else {
24-
window.addEventListener('load', loadImage, false);
25-
}
29+
});
2630
});
2731
return Promise.resolve('');
2832
};
2933

3034
exports.instantiate = function(load) {
31-
// we don't want to unpack the promise here, as it delay the execution of the
32-
// consumer. I couldn't find a better way to not unpack the Promise.
33-
return { promise: load.metadata.imgPromise };
35+
return {
36+
start: load.metadata.start,
37+
load: load.metadata.load
38+
};
3439
};

0 commit comments

Comments
 (0)