Skip to content

Commit

Permalink
fix: audit incorrectly flagging images as above the fold (#10891) (#1…
Browse files Browse the repository at this point in the history
…1617)

* fix: audit incorrectly flagging images as above the fold (#10891)

Previously used �lement.offsetTop to find the y position of the image, which does not work when the element parent has a position: relative property.
Instead, this uses �lement.getBoundingClientRect().y top get real y position of the image.
There's one issue though, which is that getBoundingClientRect returns the position relative to the user's viewport, not the absolute position.
So, add window.scrollY to the value to cancel that effect out, and you have the element's absolute position.

https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY

* chore: add changeset
  • Loading branch information
abubakriz authored Aug 5, 2024
1 parent da86d54 commit 196092a
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/shy-bees-look.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fix toolbar audit incorrectly flagging images as above the fold.
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ export const perf: AuditRuleWithSelector[] = [
match(element) {
const htmlElement = element as HTMLImageElement | HTMLIFrameElement;
// Ignore elements that are above the fold, they should be loaded eagerly
if (htmlElement.offsetTop < window.innerHeight) return false;
const elementYPosition = htmlElement.getBoundingClientRect().y + window.scrollY
if (elementYPosition < window.innerHeight) return false;

// Ignore elements using `data:` URI, the `loading` attribute doesn't do anything for these
if (htmlElement.src.startsWith('data:')) return false;
Expand All @@ -54,7 +55,8 @@ export const perf: AuditRuleWithSelector[] = [
const htmlElement = element as HTMLImageElement | HTMLIFrameElement;

// Ignore elements that are below the fold, they should be loaded lazily
if (htmlElement.offsetTop > window.innerHeight) return false;
const elementYPosition = htmlElement.getBoundingClientRect().y + window.scrollY
if (elementYPosition > window.innerHeight) return false;

// Ignore elements using `data:` URI, the `loading` attribute doesn't do anything for these
if (htmlElement.src.startsWith('data:')) return false;
Expand Down

0 comments on commit 196092a

Please sign in to comment.