Find Images Missing Width Height Using JS in Chrome Console

Find Images Missing Width Height Using JS in Chrome Console

Website optimization is critical in delivering a seamless user experience, especially as page load times and stability become key ranking factors for search engines. One often overlooked issue is layout shifts that happen as content loads. Layout shifts are visually disruptive and frustrating for users, leading to poor user experience scores. This instability can be triggered by images or other media elements that don’t have defined dimensions, causing content to move around unexpectedly. By addressing these issues proactively, we can ensure better performance metrics and a more predictable, smooth page rendering process, improving both usability and SEO.

When optimizing websites for performance and layout stability, one common issue developers face is images without explicit width and height attributes. These missing attributes can cause layout shifts, affecting user experience and Core Web Vitals, especially Cumulative Layout Shift (CLS).

In this post, I’ll show you a quick way to identify images missing width and height attributes using JavaScript directly in the Chrome Developer Console.

The Problem

When <img> tags lack defined width and height, the browser doesn’t know how much space the image will take up until it loads. This can cause page content to “jump” as images load in, exactly the kind of instability we want to avoid.

The Solution (in 1 minute)

You can run the following JavaScript snippet in your browser’s console to detect which images are missing these attributes:

Copy & Paste this into Chrome DevTools Console:

(() => {
const images = document.querySelectorAll('img');
const withoutDimensions = Array.from(images).filter(img =>
!img.hasAttribute('width') || !img.hasAttribute('height')
);
console.log(`Total <img> tags: ${images.length}`);
console.log(`Images without explicit width and/or height: ${withoutDimensions.length}`);
console.log('These images:', withoutDimensions);
})();

What This Does

  • document.querySelectorAll('img'): Grabs all image elements on the page.

  • .filter(...): Filters out those missing either a width or height attribute.

  • console.log(...): Shows a summary and lists the affected image elements in the console.


Bonus Tip: Why Not Just Use CSS?

Setting image dimensions in CSS is great for layout, but HTML attributes help browsers allocate space before the image loads. This is especially important for responsive images and for minimizing layout shifts during rendering.

So ideally, use both:

<img src="example.jpg" width="600" height="400" style="width: 100%; height: auto;">

Wrap-Up

This quick check is a great first step in improving your site’s visual stability. Integrate it into your manual QA process or even as part of automated audits with tools like Lighthouse or Puppeteer.

Happy debugging!