20/05/2022
By Imran M
By Imran M
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.
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.
You can run the following JavaScript snippet in your browser’s console to detect which images are missing these attributes:
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.
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:
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!