两种加载图片的方式,为什么使用ajax更快?
我有两种加载图像的方法,以测试加载速度。
第一:
var img = document.createElement("img");
var date1 = new Date().getTime();
img.src = "xxx.png";
img.onload = function() {
var date2 = new Date().getTime();
var delta = date2 - date1;
};
第二:
var date1 = new Date().getTime();
$.ajax({ url: "xxx.png",
data: { _s: new Date().getTime(), },
success: function () {
var date2 = new Date().getTime();
var delta = date2 - date1;
}
});
以上两种方式我已经测试过很多次了。第二个比第一个慢 30%,但我不知道为什么。谁能告诉我为什么?
I have two ways for loading a image, to test the loading speed.
First:
var img = document.createElement("img");
var date1 = new Date().getTime();
img.src = "xxx.png";
img.onload = function() {
var date2 = new Date().getTime();
var delta = date2 - date1;
};
Second:
var date1 = new Date().getTime();
$.ajax({ url: "xxx.png",
data: { _s: new Date().getTime(), },
success: function () {
var date2 = new Date().getTime();
var delta = date2 - date1;
}
});
The above two ways I've tested many times. The second is 30% slower than the first, but I don't know why. Can anyone tell me why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
任何时候您将硬编码浏览器功能(ie、
img.src="xxx.png"
加载图像)与复杂的 JavaScript 操作(ie ,$.ajax(几乎任何东西)
),JavaScript 代码将会丢失。解释型脚本语言很难与它们正在编写的编译代码的速度相匹配。Any time you compare a hard-coded browser function (i.e.,
img.src="xxx.png"
loading an image) to a complex JavaScript operation (i.e.,$.ajax(almost anything)
), the JavaScript code is going to lose. Interpreted scripting languages have a hard time matching the speed of the compiled code they're scripting.当您将文件作为图像加载时,浏览器会解码“.png”编码以准备显示图像。在知道这是一个好的图像之前,它不会调用您的“加载”处理程序。在第二种情况下,您只是获取数据,因此浏览器不关心它是否是有效的“.png”文件。
无论如何,这是我的赌注。我非常确定,如果您以第一种方式加载随机数据文件(而不是图像),则永远不会调用您的“加载”处理程序。
编辑 那么,原始问题中的“错误”使得这个答案背后的猜测基本上毫无价值。 (最初的问题是第二个 - ajax - 比通过新构建的图像加载更快。)
When you load the file as an image, the browser decodes the ".png" encoding to prepare the image for display. It doesn't call your "load" handler until it knows it's a good image. In the second case, you're just fetching the data, so the browser doesn't care whether it's a valid ".png" file or not.
That's my bet, anyway. I'm pretty sure that if you loaded a random data file (not an image) the first way, your "load" handler would never be called.
edit Well the "mistake" in the original question makes the speculation behind this answer basically worthless. (The original question read that the second — ajax — was faster than loading via a newly-constructed image.)