Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions src/core/a-assets.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,18 +57,21 @@ class AAssets extends ANode {
for (i = 0; i < imgEls.length; i++) {
imgEl = fixUpMediaElement(imgEls[i]);
loaded.push(new Promise(function (resolve, reject) {
// Bind the current img to a local so onload below does not close
// over the shared outer loop variable.
var el = imgEl;
// Set in cache because we won't be needing to call three.js loader if we have.
// a loaded media element.
if (imgEl.complete) {
THREE.Cache.add('image:' + imgEls[i].getAttribute('src'), imgEl);
if (el.complete) {
THREE.Cache.add('image:' + el.getAttribute('src'), el);
resolve();
return;
}
imgEl.onload = function () {
THREE.Cache.add('image:' + imgEls[i].getAttribute('src'), imgEl);
el.onload = function () {
THREE.Cache.add('image:' + el.getAttribute('src'), el);
resolve();
};
imgEl.onerror = reject;
el.onerror = reject;
}));
}

Expand Down
28 changes: 28 additions & 0 deletions tests/core/a-assets.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,34 @@ suite('a-assets', function () {
document.body.appendChild(sceneEl);
});

test('caches image loaded asynchronously alongside media element', function (done) {
var assetsEl = this.el;
var sceneEl = this.scene;

// Use a cache-busted src so the browser has to actually fetch, making
// imgEl.complete false when the Promise executor runs and forcing the
// onload path to be exercised.
var src = IMG_SRC + '?async-load-test';
THREE.Cache.remove('image:' + src);

var img = document.createElement('img');
img.setAttribute('src', src);
assetsEl.appendChild(img);

// A sibling media element ensures the image onload callback is
// verified alongside a non-trivial asset list.
var audio = document.createElement('audio');
audio.setAttribute('src', '');
assetsEl.appendChild(audio);

sceneEl.addEventListener('loaded', function () {
assert.equal(THREE.Cache.get('image:' + src), img);
done();
});

document.body.appendChild(sceneEl);
});

test('does not wait for media element without preload attribute', function (done) {
var el = this.el;
var scene = this.scene;
Expand Down
Loading