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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay