Don't load hidden images

前端 未结 7 1123
旧时难觅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.

    <img style="display: none; height: auto; width:100%; background-image: 
    url('img/1078x501_1.jpg'); background-size: cover;" class="center-block 
    visible-lg-block" src="img/400x186_trans.png" alt="pic 1">
    

    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 <img> 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:

    <img style="display: none; height: auto; width:100%; background-image: url('img/1078x501_1.jpg'); background-size: cover;" class="center-block visible-lg-block" src="img/400x186_trans.png" alt="pic 1">
    <img style="display: none; height: auto; width:100%; background-image: url('img/517x240_1.jpg'); background-size: cover;" class="center-block visible-md-block" src="img/400x186_trans.png" alt="pic 1">
    <img style="display: none; height: auto; width:100%; background-image: url('img/400x186_1.jpg'); background-size: cover;" class="center-block visible-sm-block" src="img/400x186_trans.png" alt="pic 1">
    

    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!

    0 讨论(0)
提交回复
热议问题