在网页中加载图片更快

sas*_*asi 23 html jquery image twitter-bootstrap-3

在Web应用程序中,当我单击应该从服务器加载图像的链接时,由于图像大小约为3MB - 5 MB,因此需要花费太多时间,因为图像分辨率问题,我们无法缩小尺寸.

放置高度和宽度有一种解决方案,但我们无法为图像放置高度和宽度.我们怎么解决呢?

我正在将服务器中的图像加载到div中

<div>
 <img src="http://upload.wikimedia.org/wikipedia/commons/1/15/Srtm_ramp2.world.21600x10800.jpg"/>
</div>
Run Code Online (Sandbox Code Playgroud)

小智 12

有许多解决方案可供管理大型图像:

尝试降低文件大小(3-5MB太高恕我直言):

  • 删除所有元数据
  • 降低分辨率/像素密度
  • 减少图像的高度/宽度
  • 使用JPEG压缩
  • 在服务器上使用GZIP压缩

您还可以探索:

  • 使用CDN提供图像(允许并行加载)
  • 使用Cloudinary/IMGIX等服务,您可以动态选择所需的图像大小


小智 6

它是如何工作的我们将从HTML中删除图像,然后将它们放回使用jQuery.就那么简单.这将允许在所有其他内容完成后加载图像

PLUS,还有一个重要的附加好处:搜索引擎可以通过HTML中的内容来衡量页面加载速度,而不是事后jQuery加载的内容.这意味着当Google测量您网站的加载速度时,网页速度结果看起来会更好.这是怎么做的:

首先:从HTML中删除所有大图像(我的图像恰好位于无序列表中):从HTML中删除所有大图像 在此输入图像描述

其次:添加一个jQuery代码段,在页面上的其他内容加载完毕后将它们添加回HTML:

[js]
$(window).load(function(){ // This runs when the window has loaded
var img = $(““).attr(‘src’, ‘YourImagePath/img.jpg’).load(function() {
$(“#a1?).append(img);
// When the image has loaded, stick it in a div
});
var img2 = $(““).attr(‘src’, ‘YourImagePath/img2.jpg’).load(function() {
$(“#a2?).append(img2);
});
});[/js]
Run Code Online (Sandbox Code Playgroud)

完成:D


Tou*_*hid 5

对图像使用HTTP缓存标头.一旦加载的图像不会在HTTP缓存标头定义的缓存过期之前重新加载.


gue*_*314 5

尝试document利用background-image容器元素的属性在加载时加载图像; 设置容器元素display:none.这应该在浏览器中缓存图像,在实际click- 已经加载到图像中时,消除了对服务器的额外请求,document在第一次click"链接" 之前缓存在浏览器中button.上click"链接",或button,拨动display具有容器元素的属性id相同className的点击button之间"block","none"; 在每个click"链接" 处显示,而不是显示图像button.

var buttons = document.querySelectorAll("button[class^=img]");

Array.prototype.slice.call(buttons)
.forEach(function(elem, index) {
  document.getElementById(elem.className)
  .style.display = "none";
  elem.onclick = function(e) {
    var img = document.getElementById(elem.className);
    img.style.display = (img.style.display === "none") ? "block" : "none";
  };
});
Run Code Online (Sandbox Code Playgroud)
body {
  width: 1800px;
  height: 1600px;
}
div[id^="img"] {
  width: 100%;
  height: 100%;
  position: relative;
}
div[id="img-1"] {
  background-image: url(http://lorempixel.com/1800/1600/cats);
}
div[id="img-2"] {
  background-image: url(http://lorempixel.com/1800/1600/technics);
}
Run Code Online (Sandbox Code Playgroud)
<button class="img-1">image 1</button>
<button class="img-2">image 2</button>
<div id="img-1">
</div>
<div id="img-2">
</div>
Run Code Online (Sandbox Code Playgroud)