Skip to content

Commit a435a03

Browse files
feat(platform): add assets cache to ImageLoader
1 parent 74fe05b commit a435a03

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

src/platform/gfx/ImageLoader.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,24 @@ import { ImageAsset } from "./ImageAsset";
66
* Loads a given image asset
77
*/
88
export class ImageLoader {
9+
private _assetsCache: Record<string, ImageAsset> = {};
10+
911
public async load(src: string): Promise<ImageAsset> {
12+
if (this._assetsCache[src]) return this._assetsCache[src];
13+
1014
return new Promise((resolve, reject) => {
1115
const type = this.getTypeFromFileName(src);
1216

1317
const image = new Image();
1418
image.onerror = reject;
1519

1620
image.onload = async () => {
17-
resolve(new ImageAsset(
21+
this._assetsCache[src] = new ImageAsset(
1822
await createImageBitmap(image),
1923
type
20-
));
24+
);
25+
26+
resolve(this._assetsCache[src]);
2127
};
2228

2329
image.src = src;

test/unit/platform/gfx/ImageLoader.test.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,24 @@ describe('platform/gfx/ImageLoader', () => {
2222
await imageLoader.load('test.png');
2323
}).rejects.toThrow('Error');
2424
})
25+
26+
it('Should cache assets that are already loaded', async () => {
27+
const spy = jest.fn().mockResolvedValueOnce(() => { });
28+
29+
global.Image = jest.fn().mockImplementation(() => ({
30+
onload: jest.fn(),
31+
set src(value: string) {
32+
spy();
33+
this.onload();
34+
}
35+
}))
36+
37+
const imageLoader = new ImageLoader();
38+
39+
await imageLoader.load('test.png');
40+
await imageLoader.load('test.png');
41+
42+
expect(spy).toHaveBeenCalledTimes(1);
43+
})
2544
})
2645
})

0 commit comments

Comments
 (0)