html - 等待 'background-image' css 样式完全加载

标签 html css angular

我的应用程序正在 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 的开发者选项“慢速 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/

    相关文章:

    HTML/CSS : flip3d how to do a 360 degrees with 4 pictures

    jquery - 使用 jQuery UI 图标作为 <li> 背景

    javascript - 生产中的 Angular 应用程序路由错误

    php - 如何在PHP代码中从数据库的第一行检索数据

    html - 防止 float 列在另一列下换行

    html - 将视频放入 iframe 中,宽度为 100% 并自动播放

    angular - 是否可以将 amazon cognito 与 Kinesis 数据流一起使用,充当生产者(生产者是 Angular 应用程序)?

    Angular - 终止 Observables 的首选方式是什么?

    html - 如何将标题放在导航栏的中间?

    php - Onchange 事件与 jquery slider 一起使用