【问题标题】:Wait for 'background-image' css style to fully load等待“背景图像”css 样式完全加载
【发布时间】:2019-02-19 09:27:15
【问题描述】:

我的应用是在 Angular 5 中开发的。 我想先加载背景图片

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

然后才加载页面的其余部分。

已经试过了:

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

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

我使用 Chrome 的开发者选项“Slow 3G Network”模拟慢速网络

在渲染图像时,所有这些事件都已被触发。找不到一种简单的方法来使它工作。 任何建议将不胜感激。非常感谢提前

【问题讨论】:

  • var img = new Image(); img.onload = () => {document.getElementById("mainDiv").style.backgroundImage = "url(" + img.src + ")" ; }; img.src = "localhost:5000/api/pictures/default/background";
  • 尝试了上面的代码,没有工作... =/
  • @CornelC 会尝试这种方法。谢谢。很快就会给出答案
  • @CornelC 在该网站的评论部分发现它在 angular 6 中不起作用,我的应用程序很快就会更新,所以这意味着我现在可以做一些额外的工作.另一条评论说,当设置为慢速 3G 网络时,它无法按预期工作...... =/

标签: html css angular


【解决方案1】:

我稍微调整了cat.'s answer 并让它工作。

本方案基于this question

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

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()">

DEMO

【讨论】:

  • 我们如何确保其他内容仅在图像之后加载
  • 它仍然无法使用慢速 3G 互联网...不知道为什么...它甚至没有调用方法“loaded()”。它只是呈现...
  • 要正确测试这个你应该禁用缓存,否则图像会立即加载。
猜你喜欢
  • 2012-11-05
  • 2012-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-17
  • 1970-01-01
  • 2017-10-21
相关资源
最近更新 更多