简体   繁体   English

如何使用javascript预加载图像

[英]How to use javascript to preload images

I have looked at a number of SO questions on how to preload images, I have created a function 我看了一些关于如何预加载图像的SO问题,我创建了一个函数

$(images).each(function () {
      var img = new Image();
      img.src = this;
      $(img).appendTo('body').css('display', 'none');
 });

Which appends the images to the dom. 将图像附加到dom。 However when I add a product to my cart, (the minicart will contain the images which have been preloaded), chrome still produces a request on that minicart image even though it has been preloaded (I can see the image in chrome developer tools). 但是,当我将产品添加到购物车时(微型购物车将包含已预加载的图像),即使该微型购物车图像已被预加载,chrome仍然会对其发出请求(我可以在chrome开发人员工具中看到该图像)。 How do I get chrome to use the image which has already been loaded instead of getting another one from the server? 如何获取Chrome浏览器以使用已加载的图片,而不是从服务器获取另一个图片?

  • your server is sending wrong headers; 您的服务器发送了错误的标题; do a search about Cache-Control , Expires , Etag and Pragma and set them to cache your images instead of download 搜索有关Cache-ControlExpiresEtagPragma并将它们设置为缓存图像而不是下载

  • chrome is buggy or it intentionally downloads the image twice. chrome有问题,或者有意将图片下载两次。 for example setting display:none too early may cause the problem, use position:absolute;left:-100000px; 例如设置display:none可能会导致问题,请使用position:absolute;left:-100000px; instead 代替

  • your developer tools is set to disable cache (click on the gear icon, then uncheck General > Disable cache (while DevTools is open) ) 您的开发者工具已设置为禁用缓存(单击齿轮图标,然后取消选中General > Disable cache (while DevTools is open)

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

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