At PIIO 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 in mobile was 3x compared to similar websites. When we started investigating we realized that they were hiding a lot of images by setting the property
none using media queries, while the goal of hiding the images was accomplished, the browser requests for the hidden images were still being sent, having 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’ work for images
As you would expect, images behave like any other element when you set the property
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 to dynamically change 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
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:
The images are not shown but the requests are made (the result would be the same if we apply
none to each image).
This doesn’t impact on the browser rendering of the DOM but it does impact on 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.
1. You can prevent the HTML containing the images from being loaded into the DOM instead of using
2. Use your images or at least the ones that you intend to hide, as background images. Background images don’t get loaded if the element is hidden.
Images get requested by the browsers even if they have the
display property set to
In order to prevent this you can implement the solution 1 mentioned before, but If you are going to be toggling the visibility of the image too much, adding and removing the image from the HTML can be an unnecessary cost of performance that you can avoid by using
Using the solution 2 is way better since you can just use CSS without having to manipulate the DOM.
I hope this article helps you understand how to manage your images when you want to hide them and avoid requesting them! Bye.