I need an explaination, how browser (Chrome/FF) load CSS images.
According to my current knowledge, images used by CSS as background-image, appear in the network tab as requests, with according CSS file as Initiator.
My current experience doesn’t cover this – I experience images, which are loaded by CSS and are visible on the page (non-lazy, above-the-fold, incognito window, DevTools with disabled cache) – but not present in the list of requests in the network tab. Certainly it goes about this page: https://www.arag.de/rechtsschutzversicherung/, about this image, on the very top of the page, as on screenshot – it doesn’t appear in the Network tab as request.
My issue: I try to count images on the page, with two console Javascripts. Nor both Javascripts, neither Network tab lists those affected images.
And so I need an explaination of browser working to understand, how can it happen, that some images don’t appear as requests, despite they are loaded by CSS with background:(img).
Here are Javascripts I count images:
- For background images:
var elems = document.getElementsByTagName('*'),
backgrounds = [];
for (var i = 0, len = elems.length; i < len; i++) {
if (window.getComputedStyle(elems[i], null).getPropertyValue('background-image') != 'none') {
backgrounds.push(window.getComputedStyle(elems[i], null).getPropertyValue('background-image'));
}
}
console.log(backgrounds);
- For img
var imageSearch = {
image_array: {},
valid_image_nodes: ["DIV", "P", "SECTION", "SPAN"],
scan_for_valid_images: function(node) {
if (node.nodeType === 1) {
if (node.nodeName === "IMG") {
this.image_array[node.getAttribute("src")] = true;
} else {
if (this.valid_image_nodes.indexOf(node.nodeName) !== -1) {
div_style = node.currentStyle || window.getComputedStyle(node, false);
if (div_style.backgroundImage !== "none") {
url = div_style.backgroundImage;
this.image_array[url.slice(4, url.indexOf(')'))] = true;
}
}
}
}
var children = node.childNodes;
for (var i = 0; i < children.length; i++) {
this.scan_for_valid_images(children[i]);
}
},
get_image_array: function() {
return Object.keys(this.image_array)
}
}
imageSearch.scan_for_valid_images(document);
imageSearch.get_image_array()
2
Answers
The cached images won’t be re-downloaded, so they won’t appear in the network tab. So these images do not affect the loading, but their status appears as: "200 OK (from disk cache)".
You need to check
:before
and:after
pseudo-elements separately because they are not standalone HTML elements, but rather parts of an element.Its not actually addressing your exact question, but it also does. You asked "How works browser with CSS images?" and you got a great answers for the problem you faced and described.
I thought that it would be good to add that, the browser will not download images if they are not display in DOM or their class being used. Moreover, will work differently. Hope I did not miss a case example here.