DEV Community

Michael Crenshaw
Michael Crenshaw

Posted on

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.