通过使用JavaScript与媒体查询配对来加载大型图像

Loading large images by using JavaScript pairing with media queries

本文关键字:加载 图像 大型 查询 媒体 JavaScript      更新时间:2023-09-26

我一直在这里查看PPK的文章,也许是在使用媒体查询时加载适当图像的更有效的方法。他建议加载它们的主要方式是将JS与CSS配对。所以代码看起来像这样:

@media all and (max-width: 900px) {
// styles go here for screen widths less than 900px wide
}
if (document.documentElement.clientWidth < 900) {
// script to load the images goes here for screen widths less than 900px wide
} 

我想弄清楚的是,加载图像的最佳方式是什么?这是使用new Image()的老派方式还是用jQuery添加内容的方式?是否有一个比另一个对服务器的压力更小?

服务器应变?不管你用哪种方式传送图像数据,并没有很多方法可以做到这一点。您只需对每个图像发出请求,服务器就会响应。你能做的最好的事情就是确保这些图片是用正确的Cache-Control标题提供的。

var img = new Image();
img.onload = function() {
  alert('woot');
};
img.src = url;

这很简单,很容易在循环中实现,并且可以在回调完成时处理回调。