【问题标题】:Chrome isn't loading images from cache when loading with javascript使用 javascript 加载时,Chrome 不会从缓存中加载图像
【发布时间】:2013-11-14 23:56:33
【问题描述】:

我一直在使用以下方法在我的网站上加载图片:

var img = document.createElement('img');
img.src = 'http://i.example.com/image-1.jpg';

Chrome 在请求标头中添加了Pragma: no-cacheCache-Control: no-cache

有没有办法可以摆脱这些标头,或者可以使用 javascript 修改它们?

【问题讨论】:

    标签: javascript image google-chrome httprequest browser-cache


    【解决方案1】:

    元素发起一个 HTTP 请求,尝试从服务器加载图像,因此我建议尝试使用 HTTP 通道来修改这些标头。试试这样的:

    httpChannel.setRequestHeader("Pragma", "new_header_state_on_your_choice_1" , false);
    httpChannel.setRequestHeader("Cache-Control", "new_header_state_on_your_choice_2" , false);
    

    关于 HTTP 通道的有用链接:https://developer.mozilla.org/en/docs/Setting_HTTP_request_headers

    如果这不起作用,请查看拦截页面(或内容)加载的方法: https://developer.mozilla.org/en-US/docs/XUL/School_tutorial/Intercepting_Page_Loads#HTTP_Observers

    另一种方法是使用 AJAX 从字面上模拟请求(AJAX 请求,然后尝试将响应加载到 ),但这可能要复杂得多。

    附:实际上有 HTML 方法来设置请求标头:

    <head>   
      <meta charset="utf-8">   
      <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
      <meta http-equiv="Pragma" content="no-cache" />
    </head>
    

    【讨论】:

    • 很遗憾,nsIHttpChannel 不在 Chrome 中。我之前尝试过元标记,但它们不起作用。 AJAX 不起作用,因为图像位于不同的子域下,我忘记在帖子中包含它。 =\
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 2011-12-15
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多