4

My app is being developed in Angular 5. I want to load the background image first

<div id="mainDiv" class="sign-in" [ngStyle]="{'background-image': 'url(' + background_source + ')'}">

and only then load the rest of the page.

Already tried:

  • window.onload
  • window.document.onload
  • document.getElementById("mainDiv").addEventListener("load", function...)

All this methods are triggered before the image fully renders on the page.

I simulate a slow network using Chrome's developer option "Slow 3G Network"

While the image is rendering all this events have already been triggered. Can't find a simple way to make it work. Any suggestion would be appreciated. Many thanks in advance

Ricardo Almeida
  • 163
  • 3
  • 14

1 Answers1

3

I tweaked cat.'s answer a little and got it to work.

This solution is based on this question

We will create a new image in memory and use the load event to detect when the image finished loading.

import { Directive, Input,  Output, EventEmitter, ElementRef } from '@angular/core';

@Directive({
  selector: '[appBackgroundImageLoaded]'
})
export class BackgroundImageLoadedDirective {
  @Output() imageLoaded: EventEmitter<boolean> = new EventEmitter<boolean>(true);

  constructor(private el: ElementRef) { }

  ngAfterViewInit() {
    const img = new Image();
    const bgStyle = getComputedStyle(this.el.nativeElement).backgroundImage
    const src = bgStyle.replace(/(^url\()|(\)$|[\"\'])/g, '');
    img.src = src;
    img.addEventListener('load', ()=> {
      this.imageLoaded.emit(true);
    });
  }
}

And the template

<div id="mainDiv" class="sign-in" [ngStyle]="{'background-image': 'url(' + background_source + ')'}" appBackgroundImageLoaded (imageLoaded)="loaded()">

DEMO

CornelC
  • 4,974
  • 1
  • 21
  • 28