Ajax不缓存请求

时间:2018-09-06 01:05:58

标签: javascript file caching

我如何使用JS获取文件的内容,让浏览器缓存文件

一种可能的方法是使该文件成为.js并使其为var SuperVar = 'BASE64-ENCODED-CONTENT'(使用base64来转义特殊字符),但是对实际内容的访问和维护确实变得很困难。 我毕竟要尝试使用普通文件。

由于文件大小为1-100 KB且数量不限,因此localStorage也不可行(空间将用完)。

尝试使用<iframe>。浏览器可以很好地解析.html文件。文件必须以<html>开头,否则它们将被包裹在<pre>标记中。 IE通过其他文件类型创建一个<object>并提供文件供下载。

重点是JS可以在多个页面加载中使用相同的文件内容,而不必每次都下载它们。

2 个答案:

答案 0 :(得分:0)

如果服务器配置正确且发出GET请求,则只需使用AJAX,它将使用缓存。

btn.onclick = function() {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    console.log(xhr.response.substr(0, 20));
  };
  xhr.open('GET', 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js');
  xhr.send();
};
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Open your dev-tools Network panel to see how it has been transferred.</p>
<button id="btn">request jQuery</button>

答案 1 :(得分:0)

您必须从服务器发送缓存控制标头,以使浏览器缓存您的Ajax请求。

index.html

<button id="btn">GET</button>
<script>
    btn.onclick = function() {
        var xhr = new XMLHttpRequest();
        xhr.onload = function() {
            console.log(xhr.response);
        };
        xhr.open('GET', 'cached.php');
        xhr.send();
    };
</script>

cached.php

<?php
header('Cache-Control: private, must-revalidate, max-age=60');
echo file_get_contents("file.any");

file.any

Contents
of
File...
  

您将看到状态码200,但是如果您选中 Size 列,   在chrome开发人员工具中,您可以查看它是否是从缓存加载的。

chrome developer tools network panel