简体   繁体   English

如何在手机上不加载图像?

[英]How to not load images on mobile phones?

I am looking for the best way to make images (real img elements, no background-image property) not load on mobile phones.我正在寻找使图像(真实img元素,无背景图像属性)无法加载到手机上的最佳方法。 Since using Media Queries and setting display to none won´t make the browser stop preloading the images, I researched for better ways using plain CSS/HTML5 without JavaScript.由于使用媒体查询和设置display ,以none不需额外使浏览器停止预载的图片,我使用纯CSS / HTML5没有JavaScript的研究更好的方法。 The only way I see is using the HTML5 picture element to load the image only at certain screen widths.我看到的唯一方法是使用 HTML5 picture元素仅以特定屏幕宽度加载图像。

<picture>
   <source media="(min-width: 480px)" src="some.png">
</picture>

However the picture element is not supported by the major browsers yet, so this is not a solution either.但是目前主流浏览器还不支持图片元素,所以这也不是一个解决方案。 Do you have any other idea how to accomplish it?你有其他想法如何实现它吗? If there is no pure CSS/HTML method what would be the best way using JavaScript?如果没有纯 CSS/HTML 方法,使用 JavaScript 的最佳方法是什么?

For anyone looking for a more modern approach (as of 2019):对于任何寻求更现代方法的人(截至 2019 年):

 <picture> <source media="(min-width: 1000px)" srcset="***url of image***"> <source media="(max-width: 999px)" srcset="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==" sizes="100%"> <img src="***url of image***" alt="***Image alt***"> </picture>

  • If the width of the browser is greater than 1000px then show url of image如果浏览器的宽度大于 1000px 则显示图片的 url
  • If the width of the browser is less than 1000px then show image represented as base64 data (which can be just a 1px in size), and in this way nothing is downloaded from the server.如果浏览器的宽度小于 1000 像素,则显示以 base64 数据表示的图像(大小可以仅为 1 像素),这样就不会从服务器下载任何内容。
  • Fallback (if the browser does not support this) - use the good old tag回退(如果浏览器不支持) - 使用旧标签

It would probably be better to start from a mobile-first approach in your case.在您的情况下,从移动优先方法开始可能会更好。 Start out by not loading any images, and then with JavaScript add the images if some requirement is met.首先不加载任何图像,然后在满足某些要求时使用 JavaScript 添加图像。 For instance like so with jQuery:例如像这样使用 jQuery:

if ($(window).width() > 959) {
    $("body").append("<img/>");
}

And if you want to make it responsive/dynamic:如果您想让它具有响应性/动态性:

$(window).resize(function() {
    if ($(window).width() > 959) {
        $("body").append('<img src="path/to/img.jpg" class="responsive-image"/>');
    } else {
        $(".responsive-image").remove();
    }
}).resize();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM