In CSS, display: none is used to hide elements, but it does not prevent the browser from downloading background images. For example, if you apply the display: none style to a div element that has a CSS background image, the browser will still fetch the image, even though it is not visible to the user.
However, when discussing images within the <img> tag, using display: none behaves differently. For <img> tags, most modern browsers optimize loading; if an image is hidden using display: none, the browser may delay loading it or completely skip loading it if the image is not visible to the user.
This behavior is not consistent across all browsers and may change with updates. Generally, if you want to prevent image loading, the best practice is to omit the image from the HTML code. If you need to load the image after user interaction, you can dynamically insert the image tag or load it on demand using JavaScript.
For example, consider a webpage that includes the following HTML and CSS code:
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image Loading Example</title> <style> .hidden { display: none; } </style> </head> <body> <img src="example.jpg" alt="Example Image" class="hidden"> </body> </html>
In the above code, even with the .hidden class applying display: none, some browsers may still download example.jpg. However, if you want to ensure the image is not preloaded, you can control loading by dynamically setting the image's src attribute using JavaScript:
javascriptdocument.addEventListener('DOMContentLoaded', function() { // Suppose the user performs an action, such as clicking a button document.getElementById('loadImageButton').addEventListener('click', function() { var img = document.getElementById('exampleImage'); img.src = 'example.jpg'; img.classList.remove('hidden'); }); });
In this example, the image is only loaded after the user clicks a button, so example.jpg is not downloaded during the initial page load.