Press enter or click to view image in full size
We are always looking for ways to improve how our clients manage their images, we have made that part of our mission and part of our culture.
Working with one of our clients, we noticed that their image traffic on mobile was three times more, compared to similar websites. When we started investigating, we realized that they were hiding a lot of images by setting the property display to none using media queries.
While the goal of hiding the images was accomplished, the browser requests for the hidden images were still being sent, which had a direct negative impact on the site load performance.
Setting display:none to images or to image containers does not prevent the browsers from requesting the image.
How “display:none” Works for Images
As you would expect, images behave like any other element when you set the property display to none, the image is not shown and doesn’t occupy any space on the DOM.
The problem is that browsers, due to the possibility of a script dynamically changing an element of the DOM, will load every element present in the DOM, and if the images are hidden but are in the DOM then they’ll send the network request for that image.
This means that, in the case of an image, it is going to be requested anyway when, in most case scenarios, you are not going to use it.
Let’s take a look at an example:
In the code above, we set display:noneto a div that contains four images to hide them from the DOM.
If we take a look at the network when loading this HTML, this is the result:
Press enter or click to view image in full size
The images are not shown but the requests are made (the result would be the same if we apply display:none to each image).
This doesn’t impact the browser rendering of the DOM but it does impact the site content load.
If you are going to be toggling the visibility of the image, then this is not a big problem, it may even be better if it is already loaded.
But, if you are not planning to show the images or the chances of showing them are really low, then this situation is actually a problem.