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

前端 未结 17 2269
再見小時候
再見小時候 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:45

    ** 2019 Answer **

    In a normal situation display:none doesn't prevent the image to be downloaded

    /*will be downloaded*/
    
    #element1 {
        display: none;
        background-image: url('https://picsum.photos/id/237/100');
    }
    

    But if an ancestor element has display:none then the descendant's images will not be downloaded

    
    /* Markup */
    
    
    /* Styles */ #father { display: none; } /* #son will not be downloaded because the #father div has display:none; */ #son { background-image: url('https://picsum.photos/id/234/500'); }

    Other situations that prevent the image to be downloaded:

    1- The target element doesn't exist

    /* never will be downloaded because the target element doesn't exist */
    
    #element-dont-exist {
        background-image: url('https://picsum.photos/id/240/400');
    }
    

    2- Two equal classes loading different images

    /* The first image of #element2 will never be downloaded because the other #element2 class */
    
    #element2 {
        background-image: url('https://picsum.photos/id/238/200');
    }
    
    /* The second image of #element2 will be downloaded */
    
    #element2 {
        background-image: url('https://picsum.photos/id/239/300');
    }
    

    You can watch for yourself here: https://codepen.io/juanmamenendez15/pen/dLQPmX

提交回复
热议问题