From 013eb44d52d5aa63576a6c8ba99d9b9ec59cbf96 Mon Sep 17 00:00:00 2001 From: Johann Schopplich Date: Tue, 12 Nov 2024 23:18:10 +0100 Subject: [PATCH] perf: outsource check for descendant of picture --- packages/core/src/lazyLoad.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/packages/core/src/lazyLoad.ts b/packages/core/src/lazyLoad.ts index 9284022..9b2e695 100644 --- a/packages/core/src/lazyLoad.ts +++ b/packages/core/src/lazyLoad.ts @@ -103,10 +103,8 @@ export function loadImage( image: HTMLImageElement, onImageLoad?: (image: HTMLImageElement) => void, ) { - const isChildOfPictureElement = image.parentElement?.tagName.toLowerCase() === 'picture' - // Skip preloading its `data-src` or `data-srcset` to avoid unnecessary requests - if (isChildOfPictureElement) { + if (isDescendantOfPicture(image)) { updatePictureSources(image) updateImageSrcset(image) updateImageSrc(image) @@ -206,10 +204,7 @@ function updateSizesAttribute( element.sizes = `${width}px` // Calculate the `sizes` attribute for sources inside a `` element - if ( - element.parentElement?.tagName.toLowerCase() === 'picture' - && !options?.skipChildren - ) { + if (isDescendantOfPicture(element) && !options?.skipChildren) { for (const sourceTag of [...element.parentElement.getElementsByTagName('source')]) { updateSizesAttribute(sourceTag, { skipChildren: true }) } @@ -261,3 +256,7 @@ function getOffsetWidth(element: HTMLElement | HTMLSourceElement) { ? element.parentElement?.getElementsByTagName('img')[0]?.offsetWidth : element.offsetWidth } + +function isDescendantOfPicture(element: HTMLElement): element is HTMLElement & { parentElement: HTMLPictureElement } { + return element.parentElement?.tagName.toLowerCase() === 'picture' +}