Skip to content

Commit

Permalink
fix(common): forward sizes and srcset to preload link tag
Browse files Browse the repository at this point in the history
Set imagesrcset and imagesizes on preload `<link>` tag
  • Loading branch information
yharaskrik committed Oct 3, 2022
1 parent 0d7bc3d commit ea32daa
Showing 1 changed file with 17 additions and 5 deletions.
Expand Up @@ -291,6 +291,13 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
*/
@Input() srcset?: string;

/**
* Value of the `sizes` attribute if set on the host `<img>` element.
* This input is exclusively read to pass along to the preload `<link>` attribute for this image.
* @internal
*/
@Input() sizes?: string;

ngOnInit() {
if (ngDevMode) {
assertNonEmptyInput(this, 'ngSrc', this.ngSrc);
Expand Down Expand Up @@ -330,15 +337,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.
const rewrittenSrc = this.getRewrittenSrc();
this.setHostAttribute('src', rewrittenSrc);
this.setHostAttribute('src', this.getRewrittenSrc());

const rewrittenSrcset = this.getRewrittenSrcset();

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

if (this.isServer && this.priority) {
this.createPreloadLinkTag(rewrittenSrc);
this.createPreloadLinkTag(this.ngSrc, rewrittenSrcset, this.sizes);
}
}

Expand Down Expand Up @@ -394,7 +402,7 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
this.renderer.setAttribute(this.imgElement, name, value);
}

private createPreloadLinkTag(url: string): void {
private createPreloadLinkTag(url: string, srcset: string, sizes?: string): void {
if (ngDevMode) {
if (this.preloadedImages.size >= DEFAULT_PRELOADED_IMAGES_LIMIT) {
throw new RuntimeError(
Expand All @@ -415,6 +423,10 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
preload.setAttribute('as', 'image');
preload.href = url;
preload.rel = 'preload';
if (sizes) {
preload.imageSizes = sizes;
}
preload.imageSrcset = srcset;

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

0 comments on commit ea32daa

Please sign in to comment.