Skip to content

Commit

Permalink
perf: outsource check for descendant of picture
Browse files Browse the repository at this point in the history
  • Loading branch information
johannschopplich committed Nov 12, 2024
1 parent 8a6df9f commit 013eb44
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions packages/core/src/lazyLoad.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -206,10 +204,7 @@ function updateSizesAttribute(
element.sizes = `${width}px`

// Calculate the `sizes` attribute for sources inside a `<picture>` 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 })
}
Expand Down Expand Up @@ -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'
}

0 comments on commit 013eb44

Please sign in to comment.