Контент в ngOnInit или ngAfterViewInit не должен загружаться до тех пор, пока не будут загружены все изображения в тегах ‹IMG›

Я использую Angular 8 для веб-приложения на основе блога. Данные пока хранятся в файле json, даже изображения загружаются вместе с путем.

JSON-данные

[
    {
        "imgSrc": "./assets/images/dalai-hills-1.jpg",
        "destination": "Dalai Hills",
        "introTitle": "through happy valley, to a picturesque place",
        "place": "mussoorie, uttarakhand",
        "description": "Lorem ipsum dolor sit amet, no elitr tation delicata cum, mei in causae deseruisse.",
    }
]

imgSrc решает, какое изображение загрузить. Все изображения уже оптимизированы и находятся в папке с ресурсами.

Шаблон

<article class="blog-card" style="border-top: 0;" *ngFor="let blog of blogsList">
    <div class="blog-img-wrap" style="min-height: 200px;">
        <a href="#"">
            <img loading="lazy" class="img-fluid blog-img" src="{{ blog.imgSrc }}" alt="blog-image-1">
        </a>
    </div>
</article>

Скажем, на странице блогов при загрузке загружается 12 изображений из-за , я хочу, чтобы страница загружалась только после загрузки всех изображений.

Я не получаю конкретного ответа на stackoverflow. В настоящее время существует очень небольшая разница в доли секунд между загрузкой текста и изображений, но это выглядит странно.

Любые решения на том же самом?

P.S: я хочу избежать jQuery.


person Prashant Saxena    schedule 24.05.2020    source источник


Ответы (1)


Вы можете;

  1. Создавайте элементы изображения программно. (используйте HTMLImageElement)
  2. Отслеживайте их состояние загрузки. (используйте ReplaySubject и forkJoin)
  3. Когда все изображения загружены, покажите их на странице. (используйте асинхронный канал и Renderer2)

Вот пример реализации (пояснения в комментариях);

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  data = [
    {
      imgSrc: "https://img.jakpost.net/c/2017/10/27/2017_10_27_34794_1509067747._large.jpg",
      destination: "destination-01",
      introTitle: "introTitle-01",
      place: "place-01",
      description: "description-01"
    },
    {
      imgSrc: "https://lakecomofoodtours.com/wp-content/uploads/gravedona-celiaa-img-0282_orig-800x600.jpg",
      destination: "destination-02",
      introTitle: "introTitle-02",
      place: "place-02",
      description: "description-02"
    },
    {
      imgSrc: "https://italicsmag.com/wp-content/uploads/2020/05/Lake-Como-5-770x550.jpg",
      destination: "destination-03",
      introTitle: "introTitle-03",
      place: "place-03",
      description: "description-03"
    }
  ];

  /* This array holds Observables for images' loading status */
  private tmp: ReplaySubject<Event>[] = [];

  blogData: BlogDataType[] = this.data.map(d => {
    const img = new Image();
    img.height = 200;
    img.width = 300;
    const evt = new ReplaySubject<Event>(1);
    img.onload = e => {
      evt.next(e);
      evt.complete();
    };
    this.tmp.push(evt);
    img.src = d.imgSrc 
    return { ...d, imgElem: img };
  });

  /* 
   * Convert images' loading status observables to a higher-order observable .
   * When all observables complete, forkJoin emits the last emitted value from each.
   * since we emit only one value and complete in img.load callback, forkJoin suits our needs.
   * 
   * when forkJoin emits (i.e. all images are loaded) we emit this.blogData so that we use it
   * in template with async pipe
   */
  blogsList: Observable<BlogDataType[]> = forkJoin(this.tmp).pipe(
    map(() => this.blogData)
  );

  constructor(private renderer: Renderer2) {}

  /* manually append image elements to DOM, used in template */
  appendImg(anchor: HTMLAnchorElement, img: HTMLImageElement) {
    this.renderer.appendChild(anchor, img);
    return "";
  }
}

interface BlogDataType {
  imgElem: HTMLImageElement;
  imgSrc: string;
  destination: string;
  introTitle: string;
  place: string;
  description: string;
}
<div *ngFor="let blog of blogsList | async">
  <div>{{blog.description}}</div>
  <a #aEl href="#">
    {{ appendImg(aEl, blog.imgElem) }}
  </a>
</div>

Вот рабочая демонстрация: https://stackblitz.com/edit/angular-ivy-ymmfz6< /а>

Обратите внимание, что эта реализация не защищена от ошибок. img.onerror также следует обрабатывать для использования в продакшене, я пропустил его для простоты.

person ysf    schedule 25.05.2020