Skip to content

Instantly share code, notes, and snippets.

@gene-ressler
Created October 22, 2024 18:38
Show Gist options
  • Select an option

  • Save gene-ressler/6681aa8f73555ca309d22126e68f950a to your computer and use it in GitHub Desktop.

Select an option

Save gene-ressler/6681aa8f73555ca309d22126e68f950a to your computer and use it in GitHub Desktop.
Loader for multiple images in Angular apps.
class ImagesLoader {
private readonly images: Map<string, HTMLImageElement>;
private readonly pendingActions: ((images: Map<string, HTMLImageElement>) => void)[] = [];
public readonly errors = new Set<string>();
private remainingCount: number;
constructor(urls: string[]) {
this.remainingCount = urls.length;
this.images = new Map<string, HTMLImageElement>(
((loader) => {
return urls.map(url => {
const image = new Image();
image.onload = () => {
// On last load, execute pending actions.
if (--loader.remainingCount == 0) {
loader.pendingActions.forEach(action => action(loader.images));
loader.pendingActions.length = 0; // Not necessary, but nice.
}
}
image.onerror = () => loader.errors.add(url);
image.src = url;
return [url, image];
})
})(this));
}
public invokeAfterLoaded(action: (images: Map<string, HTMLImageElement>) => void): void {
if (this.remainingCount == 0) {
action(this.images);
} else {
this.pendingActions.push(action);
}
}
}
let loader = new ImagesLoader([
'https://www.jqwidgets.com/wp-content/design/i/logo-jqwidgets.svg',
'https://www.greencastonline.com/assets/img/logo.png']);
loader.invokeAfterLoaded((images) => console.log("first"));
loader.invokeAfterLoaded((images) => console.log("second"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment