Don't load hidden images

前端 未结 7 1147
旧时难觅i
旧时难觅i 2020-12-02 13:19

I have a bunch of hidden images on my website. Their container DIVs have style=\"display: none\". Depending on the user\'s actions, some images may be revealed via javascrip

7条回答
  •  自闭症患者
    2020-12-02 14:24

    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.

    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!

提交回复
热议问题