Can you stop an

2020-07-01 05:01发布

Is there any way to stop an <img> tag loading its image by just using CSS? I would like to avoid using JavaScript.

This doesn't seem to work (Firebug still shows the images loading):

display: none;
visibility: hidden;

5条回答
聊天终结者
2楼-- · 2020-07-01 05:38

No — CSS only tells browsers what content should look like, it doesn’t specify loading behaviour.

The best you could do that involves CSS is to remove the <img> tag from your HTML, and replace it with an element that shows an image via CSS’s background-image property. Then the image is controlled more in the CSS than the HTML.

I still don’t think you can guarantee when the image will be downloaded though — I seem to remember early versions of Safari would download images referenced in a stylesheet even if they weren’t used on the current page? Using JavaScript (to create the <img> tag when you want the image loaded) is probably the most reliable way of controlling the timing of images getting loaded.

However, have a look at the page linked to from @Stackle’s answer to see the loading behaviour of browsers in April 2012 with different bits of CSS that hide elements with background images.

查看更多
爷的心禁止访问
3楼-- · 2020-07-01 05:45

You then set them all to be

    .img{visibility:hidden;} 

this will prevent them from making an http request but still preserves their size and spacing in the document preventing any redraws.

then when you want to show your hidden images (for instance the ones in view) you add a class to the surrounding html element and in your css tell this to be

    .show .img {visibility:visible;}

That should do it, Holmes.

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-07-01 05:52

This is an old question but today we can do it by using css only.

The answer is Yes, but not support on some browser. See this http://timkadlec.com/2012/04/media-query-asset-downloading-results/

查看更多
贼婆χ
5楼-- · 2020-07-01 05:54

Place this at the end of your style sheet:

* img { display: none !important; }
查看更多
别忘想泡老子
6楼-- · 2020-07-01 06:01

You can PRELOAD images using CSS only, but not actually delay the loading of images using CSS only.

This can, however, be done easily using something like jQuery Lazy Loader, which is MUCH easier than trying to do it by hand.

查看更多
登录 后发表回答