Skip to content

Instantly share code, notes, and snippets.

@zukasmichael
Last active January 30, 2018 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zukasmichael/8319f64849da17290461bbe49c9769d6 to your computer and use it in GitHub Desktop.
Save zukasmichael/8319f64849da17290461bbe49c9769d6 to your computer and use it in GitHub Desktop.
progressive image loading directive for angular 2+ / wrapper background css loads small image while directive loads a big one and adds it on the top
import {ImageloaderDirective} from './directives/imageloader/imageloader.directive';
@NgModule({
...
declarations: [
ImageloaderDirective
],
...
})
.image_bg_sm {
background-image: url(/assets/img/image_sm.jpg);
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
<div class="image_bg_sm" imagePreload="/assets/img/image_hd.jpg"></div>
import {Directive, ElementRef, Input} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
@Directive({selector: '[imagePreload]'})
export class ImageloaderDirective {
link: string;
tmpImg: HTMLImageElement;
constructor(el: ElementRef) {
this.link = el.nativeElement.getAttribute('imagePreload'); // get image url
this.tmpImg = new Image(); // new phantom image
this.tmpImg.src = this.link;
this.tmpImg.onload = () => { // when loaded
el.nativeElement.style.backgroundImage = 'url(' + this.link + ')'; // set hd background image
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment