代码之家  ›  专栏  ›  技术社区  ›  Ramiz Uddin

刷新iFrame(缓存问题)

  •  18
  • Ramiz Uddin  · 技术社区  · 16 年前

    我们得到了一个奇怪的问题,我们不知道究竟是什么原因。让我详细说明一下这个问题。假设我们有两个不同的html页面a.html和b.html。还有一个用index.html编写的小脚本:

    <html>
    
    <head>
        <script>
        function reloadFrame(iframe, src) {
            iframe.src = src;
        }
        </script>
    </head>
    
    <body>
        <form>
            <iframe id="myFrame"></iframe>
            <input type="button" value="Load a.html" onclick="reloadFrame(document.getElementById('myFrame'), 'a.html')">
            <input type="button" value="Load b.html" onclick="reloadFrame(document.getElementById('myFrame'), 'b.html')">
        </form>
    </body>
    
    </html>
    

    服务器组件正在不断更新A.html和b.html文件。问题是两个文件的内容都在服务器端成功更新。如果我们打开,我们可以看到更新的变化,但客户端得到了旧的内容,这并不显示更新的变化。

    你知道吗?

    5 回复  |  直到 10 年前
        1
  •  27
  •   Tushar    10 年前

    <head>
        <meta http-Equiv="Cache-Control" Content="no-cache" />
        <meta http-Equiv="Pragma" Content="no-cache" />
        <meta http-Equiv="Expires" Content="0" />
    </head>
    

    强制不进行缓存检查

        2
  •  12
  •   Community Mohan Dere    8 年前

    Making sure a web page is not cached, across all browsers (我认为大家一致认为第二个答案是最好的,而不是公认的答案)

    Simone的答案已经涉及到元标记。

    一个廉价的快速技巧是添加一个随机数作为GET参数:

    page_1.html?time=102398405820
    

    如果每次请求时都发生更改(例如,使用当前时间),则每次都会强制重新加载。

        3
  •  9
  •   HoBa    13 年前

    尝试以下操作:

    <script>
        var frameElement = document.getElementById("frame-id");
        frameElement.contentWindow.location.href = frameElement.src;
    </script>
    

        4
  •  0
  •   Willito    12 年前

    霍梅罗·巴博萨的解决方案非常有效。在我的例子中,页面上有不同数量的iframe,因此我做了以下操作:

    $('.some_selector').each(function () {
      var $randid = Math.floor(Math.random() * 101);
      $(this).attr({'id': 'goinOnaSafari-' + $randid});
    
      var $frame = document.getElementById('goinOnaSafari-' + $randid);
      $frame.contentWindow.location.href = $frame.src;
    });
    
        5
  •  0
  •   Michael Freidgeim    4 年前

    我想把 Vishwas comment Pekka’s answer

    //ensure iframe is not cached
    function reloadIframe(iframeId) {
        var iframe = document.getElementById(iframeId);
        var d = new Date();
        if (iframe) {
            iframe.src = iframe.src + '?ver=' + d.getTime();
            //alternatively frameElement.contentWindow.location.href = frameElement.src; //This will force the iframe to be reloaded even if it was cached by the browser
        }
    }
    reloadIframe('session_storage_check');
    
        6
  •  -1
  •   Community Mohan Dere    7 年前

    对于一个可能的解决方案,将“cache参数”传递给对a.html和b.html的调用。例如

    HTML格式

    <input type="button" value="Load a.html" onclick="cacheSafeReload('a.html');">
    

    function cacheSafeReload(urlBase) {
        var cacheParamValue = (new Date()).getTime();
        var url = urlBase + "?cache=" + cacheParamValue;
        reloadFrame(document.getElementById('myFrame'), url);
    }