DEV Community

Daniel - JS Craft
Daniel - JS Craft

Posted on

2 1

Using a CSS display none will still trigger an HTTP request for images

Let's say we have the following code:

<img src="cat.jpg" style="display:none" />
Enter fullscreen mode Exit fullscreen mode

This will still trigger the expensive HTTP call to get this image. This can be checked in Devtools - Network tab.

The image will still be requested even if we use a media query.

@media (max-width: 500px) {
    img {
        display: none; 
    } 
}
Enter fullscreen mode Exit fullscreen mode

And even in the case when an img is inside of a hidden parent, the request is still made.

<div class="hide">
    <img src="cat.jpg" />
</div> 
Enter fullscreen mode Exit fullscreen mode

However, using the image as a CSS background-image on a hidden div will not trigger the call.

<div style="hide">
    <div style="background: url(cat.jpg)"></div> 
</div> 
Enter fullscreen mode Exit fullscreen mode

I've discovered this while playing with the fun Request Quest made by Jake Archibald. It teaches you in a fun way how and when the requests are made for images. Also from a Javascript perspective. Good to know from a performance point of view.

Cool stuff ! :)

First published on http://www.js-craft.io/blog/using-a-css-display-none-will-still-trigger-an-http-request-for-images/

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (2)

Collapse
 
alohci profile image
Nicholas Stimpson

Good to know, but don't let it screw up your accessibility. If you want the image at all, then at some point you're going turn display:none off. With a background image, the unsighted users never going to know that the new information has been presented. With an img element, the alt value will let them know.

Collapse
 
js_craft_hq profile image
Daniel - JS Craft

good point :) Thanks

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs