If an asset (for example, a .jpg image) is found in the DOM, but marked with 'display: none' CSS, which browsers will download that asset, even though it doesn't technically display it to the user?
This is a website load speed question. I want to know how CSS display properties affect page load time. This question has been asked before on StackOverflow. However, that was two years ago, and I've heard rumors that things have changed since then.
Internet Explorer versions 6+ all appear to load the image. Firefox doesn't appear to load the image in versions 3-5, but do load the image from version 6 and up. As for Chrome, the image would be loaded at least as far back as version 14. Safari 4 and up also load the image.
Run the test yourself: http://jsfiddle.net/jonathansampson/4L9adwcu/
(function () {
var image = document.createElement( "img" ),
timeout = setTimeout(function timeout () {
alert( "Image was not loaded." );
}, 3000);
function loaded () {
clearInterval( timeout );
alert( "Image was loaded." );
}
if ( image.addEventListener ) {
image.addEventListener( "load", loaded );
} else if ( image.attachEvent ) {
image.attachEvent( "onload", loaded );
}
image.style.display = "none";
image.src = "http://gravatar.com/avatar/a84a8714fd33f6676743f9734a824feb";
document.body.appendChild( image );
}());
If I had to speculate as to why this was the case, I suspect it would have something to do with loading DOM resources as quickly as possible so they will be ready when they're needed. If the Image is not added to the document (meaning we remove document.body.appendChild...
) it will not be requested.
You can keep images from being loaded by using a data-*
attribute instead. When the image is needed, swap the src
value out for the data-src
value, and at that point the browser will load the image:
<img data-src="http://example.com/dont-load-me.png" />
The actual swap would be fairly straight-forward:
imageReference.src = imageReference.getAttribute( "data-src" );
I should mention that I am an engineer on the Internet Explorer team.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With