Does “display:none” prevent an image from loading?

前端 未结 17 2167
再見小時候
再見小時候 2020-11-22 05:13

Every responsive website development tutorial recommends using the display:none CSS property to hide content from loading on mobile browsers so the website load

17条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 05:49

    If you make the image a background-image of a div in CSS, when that div is set to 'display: none', the image will not load.

    Just expanding on Brent's solution.

    You can do the following for a pure CSS solution, it also makes the img box actually behave like an img box in a responsive design setting (that's what the transparent png is for), which is especially useful if your design uses responsive-dynamically-resizing images.

    
    

    The image will only be loaded when the media query tied to visible-lg-block is triggered and display:none is changed to display:block. The transparent png is used to allow the browser to set appropriate height:width ratios for your block (and thus the background-image) in a fluid design (height: auto; width: 100%).

    1078/501 = ~2.15  (large screen)
    400/186  = ~2.15  (small screen)
    

    So you end up with something like the following, for 3 different viewports:

    
    
    
    

    And only your default media viewport size images load during the initial load, then afterwards, depending on your viewport, images will dynamically load.

    And no javascript!

提交回复
热议问题