等待“背景图像" css样式完全加载 [英] Wait for 'background-image' css style to fully load

查看:184
本文介绍了等待“背景图像" css样式完全加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序正在Angular 5中开发. 我想先加载背景图片

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.

已经尝试:

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

所有这些方法都是在图像在页面上完全呈现之前触发的.

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

我使用Chrome的开发者选项慢3G网络"模拟慢速网络

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

推荐答案

我调整了

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

此解决方案基于此问题

我们将在内存中创建一个新图像,并使用load事件检测图像何时完成加载.

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);
    });
  }
}

和模板

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

演示

这篇关于等待“背景图像" css样式完全加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆