我的应用程序正在 Angular 5 中开发。
我想先加载背景图片
<div id="mainDiv" class="sign-in" [ngStyle]="{'background-image': 'url(' + background_source + ')'}">
然后才加载页面的其余部分。
已经尝试过:
所有这些方法都是在图像完全呈现在页面上之前触发的。
我使用 Chrome 的开发者选项“慢速 3G 网络”模拟慢速网络
在渲染图像时,所有这些事件都已被触发。找不到一个简单的方法来使它工作。
任何建议将不胜感激。提前谢谢了
最佳答案
我调整了 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
关于html - 等待 'background-image' css 样式完全加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52334123/