Why does `display: none` not load background image?

Viewed 233

I am having a hard time to wrap my head around this quiz question:

On page load, will mypic.jpg get downloaded by the browser?

#test1 {
    display: none;
}
#test2 {
    background-image: url('http://www.dumpaday.com/wp-content/uploads/2017/01/random-pictures-116.jpg');
    visibility: hidden;
}
<div id="test1">
    <span id="test2"></span>
</div>

The answer is no. Why is that? Trying above doesn't load the image. But loading happens when I switch to display: block;

Does that have something with element space to be preserved using hidden visibility?

I am also confused because the previous question says display: none does load the background image although not in this case with a hidden descendant, and this thread talks about browsers are getting smarter and prevent the loads. So where is the truth?

1 Answers

So I found this interesting because I didn't know about that. To conclude the image won't load if the item or one of its parents settings is display: none. Is it because browsers get smarter? I don't think so. I tried the following:

#test1 {
    display: none;
}
<div id="test1">
   <img src="http://www.dumpaday.com/wp-content/uploads/2017/01/random-pictures-116.jpg"/>
</div>

In the Network tab of the developer-tools you can see that the image gets loaded. So it differs from your example. My thought is that display: none does not draw the element (fact) and so no style will be applied to itself or one of its childs (thought). Basically background-image: url('...'); won't be executed because there is no need in applying the style to this element because it won't draw anyway.

I hope this helped you understand :)

Related