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" />

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; 
    } 
}

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> 

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

<div class="hide">
    <div style="background: url(cat.jpg)"></div> 
</div> 

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 ! 🙂

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X