延迟加载背景图片时防止重复请求 [英] Prevent double request when lazy loading a background-image

查看:103
本文介绍了延迟加载背景图片时防止重复请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javascript并在下载完成后使用回调函数来延迟加载背景图片.我正在使用此代码

I'm trying to lazy load a background-image using javascript and using a callback when the download is complete. I'm using this code

var img = new Image();

img.onload = function() {

    element.style.backgroundImage = 'url(' + this.src + ')';
    // Need to do other things here
}

img.src = 'path_to_image.jpg';

它在Chrome,Firefox和IE 9+上运行良好,但是在使用Safari(OSX和iOS)或Android浏览器时会向服务器发出两个请求.似乎这两个浏览器都不使用缓存.有没有在不下载每个图像两次的情况下执行此操作的想法?

It is working well on Chrome, Firefox, and IE 9+, but it makes two requests to the server when using Safari (OSX and iOS) or Android browser. It seems like these two browsers don't use cache. Any idea on how to do this without downloading every images twice?

如果有帮助,我就不需要与IE 10及更早版本兼容

If it helps, I don't need it to be compatible with IE 10 and older

推荐答案

我通过在传输图像文件时设置Cache-Control标头解决了这一问题.显然,如果您没有另外指定,Safari会认为图像会立即过期,因此它们在预加载和首次使用之间到期.

I solved this by setting a Cache-Control header when transmitting the image files. Apparently images are considered by Safari to expire immediately if you do not specify otherwise, so they are expiring between preload and first use.

您可能希望使用Web服务器指令来更改这些标头,如在我发现问题的一般解决方案时所建议的那样(

You'll probably want to use a Web server directive to change these headers, as suggested where I found the general solution to my problem (jQuery Pre-load Not Caching in Chrome or Safari). Enabling a one-day cache on Apache should look like this:

<FilesMatch "\.(gif|jpeg|jpg|png|svg)$">
    Header set Cache-Control "public, max-age=86400"
</FilesMatch>

对我来说,快速尝试验证实际上并没有用,但 Apache 2.4文档中的示例,所以我可能还有其他事情要做.

That didn't actually work for me in a quick attempt to verify it, but neither did the example in the Apache 2.4 docs so I probably have something else going on.

在我的情况下,我恰巧是在控制器中生成原始图像,因此最终在返回它们之前,使用了应用程序框架的功能(CakePHP 3)来设置标头:

In my case I happened to be generating original images in a controller, so I ended up setting the headers using a feature of my app's framework (CakePHP 3) before I returned them:

$this->response->cache('-10 seconds', '+40 seconds');

这导致Cake在响应中添加了三个标题:

This results in Cake adding three headers to the response:

Last-Modified:   Fri, 24 Jun 2016 10:20:14 GMT
Expires:         Fri, 24 Jun 2016 10:21:04 GMT
Cache-Control:   public, max-age=40

那让我担心客户端和服务器之间的时钟差异,但是根据 HTTP/1.1规范:

That got me worried about clock differences between the client and the server, but according to the HTTP/1.1 spec:

如果响应中同时包含Expires标头和max-age指令,则即使Expires标头的限制性更强,max-age指令也会覆盖Expires标头.

If a response includes both an Expires header and a max-age directive, the max-age directive overrides the Expires header, even if the Expires header is more restrictive.

这篇关于延迟加载背景图片时防止重复请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆