Skip to content

Commit

Permalink
feat(common): add <link> preload tag on server for priority img
Browse files Browse the repository at this point in the history
While in Angular Universal, for images that are priority add a preload <link> tag to the <head> to ensure the image is preloaded before it is rendered. This resolves a warning when running Lighthouse.
  • Loading branch information
yharaskrik committed Sep 4, 2022
1 parent f8e78e3 commit 38323dc
Showing 1 changed file with 21 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/

import {Directive, ElementRef, inject, Injector, Input, NgZone, OnChanges, OnDestroy, OnInit, Renderer2, SimpleChanges, ɵformatRuntimeError as formatRuntimeError, ɵRuntimeError as RuntimeError} from '@angular/core';
import {DOCUMENT, isPlatformServer} from '@angular/common';
import {Directive, ElementRef, inject, Injector, Input, NgZone, OnChanges, OnDestroy, OnInit, PLATFORM_ID, Renderer2, SimpleChanges, ɵformatRuntimeError as formatRuntimeError, ɵRuntimeError as RuntimeError} from '@angular/core';

import {RuntimeErrorCode} from '../../errors';

Expand Down Expand Up @@ -168,6 +169,8 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
private renderer = inject(Renderer2);
private imgElement: HTMLImageElement = inject(ElementRef).nativeElement;
private injector = inject(Injector);
private readonly isServer = isPlatformServer(inject(PLATFORM_ID));
private readonly document = inject(DOCUMENT);

// a LCP image observer - should be injected only in the dev mode
private lcpObserver = ngDevMode ? this.injector.get(LCPImageObserver) : null;
Expand Down Expand Up @@ -301,10 +304,16 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
this.setHostAttribute('fetchpriority', this.getFetchPriority());
// The `src` and `srcset` attributes should be set last since other attributes
// could affect the image's loading behavior.
this.setHostAttribute('src', this.getRewrittenSrc());
const rewrittenSrc = this.getRewrittenSrc();
this.setHostAttribute('src', rewrittenSrc);

if (this.rawSrcset) {
this.setHostAttribute('srcset', this.getRewrittenSrcset());
}

if (this.isServer && this.priority) {
this.createPreloadLinkTag(rewrittenSrc);
}
}

ngOnChanges(changes: SimpleChanges) {
Expand Down Expand Up @@ -358,6 +367,16 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
private setHostAttribute(name: string, value: string): void {
this.renderer.setAttribute(this.imgElement, name, value);
}

private createPreloadLinkTag(url: string): void {
const preload = this.document.createElement('link');
preload.setAttribute('fetchpriority', 'high');
preload.href = url;
preload.as = 'image';
preload.rel = 'preload';

this.document.head.appendChild(preload);
}
}

/***** Helpers *****/
Expand Down

0 comments on commit 38323dc

Please sign in to comment.