Last active
January 30, 2018 20:22
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {ImageloaderDirective} from './directives/imageloader/imageloader.directive'; | |
@NgModule({ | |
... | |
declarations: [ | |
ImageloaderDirective | |
], | |
... | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.image_bg_sm { | |
background-image: url(/assets/img/image_sm.jpg); | |
background-size: cover; | |
background-position: center; | |
background-repeat: no-repeat; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="image_bg_sm" imagePreload="/assets/img/image_hd.jpg"></div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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