DEV Community

Michael Crenshaw
Michael Crenshaw

Posted on

1 3

How much of a page is occupied by images?

I was curious how much of a page's area was occupied by images. So I hacked together a rough approximation:

function PercentOfPage(selector) {
    return [...document.querySelectorAll(selector)].reduce(
            (a, i) => a + i.offsetWidth * i.offsetHeight,
            0
        ) / (document.body.offsetHeight * document.body.offsetWidth);
}
Enter fullscreen mode Exit fullscreen mode

For my purposes I'd use const imgArea = PercentOfPage('img');.

It doesn't take into account whether the target elements are actually visible (for example, they might be positioned off-page or behind another element). But it's good enough for my purposes.

Please offer suggestions! I'd love to fine-tune this utility a bit more.

P.S.: this page is ~1% images.

Top comments (2)

Collapse
 
ben profile image
Ben Halpern

Wow, really cool!

Collapse
 
kylefilegriffin profile image
Kyle Griffin

Very interesting. The sort of thing that could have a lot of potential value to clients but nobody really bothered to code up before.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay