Do browsers request images that have been overwritten in CSS?

106 views Asked by At

Let's say I have CSS that looks like this:

#element {background-image: url("image1.png");}
#element {background-image: url("image2.png");}

Will the browser:

  • Request image1.png, then request image2.png and display it? Or...
  • Parse the CSS first, see that the selector specifying image2.png takes priority, and only request and display image2.png?
4

There are 4 answers

0
andyb On BEST ANSWER

From some quick testing with Chrome and the Developer Tools:

  • If #element does not exist then neither image is downloaded, since the browser has no matching element to apply the style to
  • If #element exists the usual CSS cascading and specificity rules apply and only image2.png will be downloaded since that rule appears after the image1.png rule.

That said, other browsers may behave differently.

0
Vintage On

When you first request a page, your browser sends arequest to the server, as you know. The browser then starts parsing the page.

When it finds a reference to an external resource, it will do yet another request for that resource. So I think that it will still load it.

0
Andy On

It parses the CSS first, and then requests the image, so image1.png would not be downloaded

0
Ryan McDonough On

If you implement a website running this in chrome you can see that the browser parses the CSS first, creates the rules & requests it needs then makes the request.

In CSS rules at the bottom of the CSS override any from the top, so the browser knows to only request images that are the final rules.