使用 javascript 预加载图像

发布于 2024-08-28 19:07:34 字数 401 浏览 1 评论 0原文

这是我的预加载脚本:

<script type="text/javascript"> 
Image_1 = new Image(1,1);
Image_1.src = "images/sprites.png";
</script>

它工作正常。我可以在标题中看到图像加载。

这是我的问题。尽管我已经预加载了 sprites.png,但我注意到,当我转到网站上仅显示整个图像的页面时,标头告诉我我的浏览器正在请求服务器再次发送图像。

我希望听起来不要太天真。但是,为什么当我之前预加载图像时浏览器会请求图像呢?浏览器是否还有其他原因需要重新请求?

另外,我将尺寸设置为 Image(1,1)。有时我不知道尺寸,因为该图像会不时更新。也许这是一个原因?

Here is my preload script:

<script type="text/javascript"> 
Image_1 = new Image(1,1);
Image_1.src = "images/sprites.png";
</script>

And it works fine. I can see in the headers the image loading.

Here's my question. Even though I have preloaded sprites.png, I notice that when I go to a page on my site that simply displays that entire image, the headers tell me my browser is requesting the server to send the image again.

I'm hoping to not sound too naive. But, why would the browser request the image when I preloaded it earlier? Are there other reasons the browser would need to re-request?

Also, I put the dimensions as Image(1,1). Sometimes I don't know the dimensions, as that image gets updated from time to time. Maybe that's a reason?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

安静 2024-09-04 19:07:34

您需要从服务器发送带有图像的 Expires 标头,以在浏览器中启用缓存。

例如在 Apache(在 .htaccess 中)

启用过期:

ExpiresActive On

按日期:

ExpiresDefault "access plus 30 days"

或按文件类型:

ExpiresByType image/gif "modification plus 5 hours 3 minutes"

You need to send an Expires header with the image from the server to enable caching in the browser.

e.g. in Apache (in .htaccess)

enable expires:

ExpiresActive On

by date:

ExpiresDefault "access plus 30 days"

or by filetype:

ExpiresByType image/gif "modification plus 5 hours 3 minutes"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文