Skip to content

Instantly share code, notes, and snippets.

@lolmaus
Created January 11, 2021 14:49
Show Gist options
  • Save lolmaus/4f70c00e22c124bf69a4e1ec99b8dd26 to your computer and use it in GitHub Desktop.
Save lolmaus/4f70c00e22c124bf69a4e1ec99b8dd26 to your computer and use it in GitHub Desktop.
An EmberJS modifier to hide an image during loading. Useful for virtual scrolling, when same image element is reused and briefly displays obsolete image when its `src` attribute is changed.
import Modifier from 'ember-modifier';
import { action } from '@ember/object';
export default class ImgLoadingModifier extends Modifier {
src?: string;
_hideClass = 'loading';
hideImage(): void {
this.element.classList.add(this._hideClass);
}
@action
showImage(): void {
this.element.classList.remove(this._hideClass);
}
handleImageLoading(): void {
this.hideImage();
(this.element as HTMLImageElement).onload = this.showImage;
}
didReceiveArguments(): void {
if (this.src !== this.args.positional[0]) {
this.src = this.args.positional[0] as string;
this.handleImageLoading();
}
}
willDestroy(): void {
(this.element as HTMLImageElement).onload = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment