简体   繁体   English

使用javascript强制图像缓存

[英]Force image caching with javascript

I am trying to clone an image which is generated randomly. 我试图克隆随机生成的图像。 Although I am using the exact same url a different image is load. 虽然我使用完全相同的URL,但是加载了不同的图像。 (tested in chrome and firefox) (在chrome和firefox中测试过)

I can't change the image server so I am looking for a pure javascript/jQuery solution. 我无法更改图像服务器,所以我正在寻找一个纯粹的javascript / jQuery解决方案。

How do you force the browser to reuse the first image? 你如何强制浏览器重用第一张图片?

Firefox: 火狐: Firefox演示

Chrome: 铬: Chrome演示

Try it yourself (maybe you have to reload it several times to see it) 自己尝试一下(也许你需要多次重装才能看到它)

Code: http://jsfiddle.net/TRUbK/ 代码: http//jsfiddle.net/TRUbK/

$("<img/>").attr('src', img_src)
$("<div/>").css('background', background)
$("#source").clone()

Demo: http://jsfiddle.net/TRUbK/embedded/result/ 演示: http//jsfiddle.net/TRUbK/embedded/result/

You can't change the image server if it isn't yours, but you can trivially write something on your own server to handle it for you. 如果图像服务器不是您的图像服务器,则无法更改图像服务器,但您可以在自己的服务器上轻松编写一些内容来为您处理。

First write something in your server-side language of choice (PHP, ASP.NET, whatever) that: 首先用你选择的服务器端语言(PHP,ASP.NET,等等)写一些东西:

  1. Hits http://a.random-image.net/handler.aspx?username=chaosdragon&randomizername=goat&random=292.3402&fromrandomrandomizer=yes and downloads it. 点击http://a.random-image.net/handler.aspx?username=chaosdragon&randomizername=goat&random=292.3402&fromrandomrandomizer=yes并下载它。 You generate a key in one of two way. 您可以通过两种方式生成密钥。 Either get a hash of the whole thing (MD5 should be fine, it's not a security-related use so worries that it's too weak these days don't apply). 要么得到整个事情的哈希(MD5应该没问题,它不是与安全相关的用途,所以担心它现在太弱了不适用)。 Or get the size of the image - the latter could have a few duplicates, but is faster to produce. 或者获得图像的大小 - 后者可能有一些重复,但生成速度更快。
  2. If the image isn't already stored, save it in a location using that key as part of its filename, and the content-type as another part (in case there's a mixture of JPEGs and PNGs) 如果图像尚未存储,请将其保存在使用该键作为其文件名的一部分的位置,并将内容类型另存为另一部分(如果存在JPEG和PNG的混合)
  3. Respond with an XML or JSON response with the URI for the next stage. 使用下一阶段的URI响应XML或JSON响应。

In your client side-code, you hit that URI through XmlHttpRequest to obtain the URI to use with your images. 在您的客户端代码中,您通过XmlHttpRequest命中该URI以获取要与您的图像一起使用的URI。 If you want a new random one, hit that first URI again, if you want the same image for two or more places, use the same result. 如果你想要一个新的随机URI,再次点击第一个URI,如果你想要两个或多个地方的相同图像,使用相同的结果。

That URI hits something like http://yourserver/storedRandImage?id=XXX where XXX is the key (hash or size as decided above). 该URI会遇到类似http://yourserver/storedRandImage?id=XXX ,其中XXX是键(哈希或大小如上所述)。 The handler for that looks up the stored copies of the images, and sends the file down the response stream, with the correct content-type. 其处理程序查找存储的映像副本,并使用正确的内容类型将文件发送到响应流中。

This is all really easy technically, but the possible issue is a legal one, since you're storing copies of the images on another server, you may no longer be within the terms of your agreement with the service sending the random images. 这在技术上非常简单,但可能的问题是合法的,因为您将图像的副本存储在另一台服务器上,您可能不再符合与发送随机图像的服务协议的条款。

The headers being sent from your random image generator script include a Cache-Control: max-age=0 declaration which is in essence telling the browser not to cache the image. 从随机图像生成器脚本发送的标头包括Cache-Control: max-age=0声明,它实质上是告诉浏览器不要缓存图像。

You need to modify your image generator script/server to send proper caching headers if you want the result to be cached. 如果希望缓存结果,则需要修改图像生成器脚本/服务器以发送正确的缓存标头。

You also need to make sure that the URL stays the same (I didn't look at that aspect since there were tons of parameter being passed). 您还需要确保URL保持不变(我没有看到那个方面,因为传递了大量的参数)。

First off, you can "force" anything on the web. 首先,您可以“强制”网络上的任何内容。 If you need to force things, then web development is the wrong medium for you. 如果你需要强迫事物,那么Web开发对你来说是错误的媒介。

What you could try, is to use a canvas element to copy the image. 你可以尝试的是使用canvas元素来复制图像。 See https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images for examples. 有关示例,请参阅https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

You can try saving the base64 representation of the image. 您可以尝试保存图像的base64表示。

Load the image in an hidden div/canvas, then convert it in base64. 将图像加载到隐藏的div / canvas中,然后在base64中进行转换。 (I'm not sure if a canvas can be hidden, nor if it is possible to convery the img using html4 tag) Now you can store the "stringified" image in a cookie, and use it unlimited times... (我不确定是否可以隐藏画布,也不确定是否可以使用html4标签来保存img)现在您可以将“字符串化”图像存储在cookie中,并无限次地使用它...

There seems to be two workarounds: 似乎有两种解决方法:

  1. If you go with the Canvas method, see if you can get the image to load onto the Canvas itself so that you can manipulate the image data directly instead of making a 2nd http request for the image. 如果您使用Canvas方法,请查看是否可以将图像加载到Canvas本身,以便您可以直接操作图像数据,而不是为图像发出第二个http请求。 You can feed the image data directly onto a 2nd Canvas. 您可以将图像数据直接提供到第二个画布上。
  2. If you're going to build a proxy, you can have the proxy remove the No-Cache directive so that subsequent requests by your browser use the cache (no guarantees here - depends on browser/user settings). 如果您要构建代理,可以让代理删除No-Cache指令,以便浏览器的后续请求使用缓存(此处不保证 - 取决于浏览器/用户设置)。

Tell it to stop getting a random image, seems to work the way you want when I add this third replace call: 告诉它停止获取随机图像,当我添加第三个替换调用时,似乎按照您想要的方式工作:

// Get the canvas element.
var background = ($("#test").css('background-image')),
img_src = background.replace(/^.+\('?"?/, '').replace(/'?"?\).*$/, '').replace(/&fromrandomrandomizer=yes/,'')  

try: 尝试:

var myImg = new Image();
myImg.src = img_src;

and then append "myImg" to where you want: 然后将“myImg”附加到您想要的位置:

$(document).append(myImg);

I did this with your fiddler scripts and got the same image every time 我用你的小提琴脚本做了这个,每次都得到相同的图像

#test {
background:url(http://a.random-image.net.nyud.net/handler.aspx?username=chaosdragon&randomizername=goat&random=292.3402&fromrandomrandomizer=yes);
width: 150px;
height: 150px;

} }

note the .nyud.net after the domain name. 请注意域名后面的.nyud.net。

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

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