簡體   English   中英

刷新iFrame(緩存問題)

[英]Refresh iFrame (Cache Issue)

我們遇到了一個奇怪的問題,我們不確定到底是什么原因造成的。 讓我詳細說明這個問題。 假設,我們有兩個不同的 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。 問題是兩個文件的內容都在服務器端成功更新。 如果我們打開,我們可以看到更新的更改,但客戶端獲取的是不顯示更新更改的舊內容。

任何的想法?

在 a.html 和 b.html 中添加這個

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

強制不進行緩存檢查

如果您可以向這些 HTML 文件添加服務器端指令,則可以發送適當的標頭以防止緩存:

確保所有瀏覽器都沒有緩存網頁(我認為共識是第二個答案是最好的,而不是公認的)

Simone 的回答已經涉及 Meta 標簽。

一個廉價的快速技巧是添加一個隨機數作為 GET 參數:

page_1.html?time=102398405820

如果每次請求都會改變(例如使用當前時間),則每次都會強制重新加載。

嘗試類似以下內容:

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

這將強制重新加載 iframe,即使它已被瀏覽器緩存

我想把Vishwas 的評論作為一個單獨的答案,擴展Pekka 的答案

//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');

Homero Barbosa 的解決方案很有魅力。 就我而言,頁面上有不同數量的 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;
});

我無法讓 HTML 工作。

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

對於 chrome 中的開發,我檢查了控制台網絡選項卡並找到了 iframe 的加載位置。 我確認它加載了 304 響應,這意味着它從緩存中加載。 右鍵單擊 -> 清除瀏覽器緩存。

不會在生產中工作,但至少有助於開發。

對於此問題的一種可能解決方案,將“緩存參數”傳遞給您對 a.html 和 b.html 的調用。 例如

HTML

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

Javascript

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM