0

How can I get the contents of a file using JS, while letting the file be cached by the browser?

One possible way is to make that file a .js and let it be var SuperVar = 'BASE64-ENCODED-CONTENT' (base64 to escape special chars), but access and maintenance of the real contents would become indeed hard. I am trying to have normal files after all.

As the files are in size of 1-100 KB and of an unlimited quantity, so is localStorage not an option (will run out of space).

Have tried with <iframe>. Browsers parse .html files somewhat fine. Files need to begin with <html> else they get wrapped in a <pre> tag. By other filetypes IE creates an <object> and offers the file for download.

The point is for JS to work with the same file contents on multiple page loads without downloading them every time.

Krupp
  • 351
  • 1
  • 5
  • 18

2 Answers2

0

You can simply use AJAX, which will use the cache, if your server is configured correctly, and if you make GET requests.

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>
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • You said "you probably have to do a GET request" which means it may also be POST? Please clarify this and "if your server is configured correctly" and any other details necessary for a cached ajax – Krupp Sep 10 '18 at 03:10
  • @Krupp I don't really have time to go into details right now sorry. But it is the same as with any other request, you need a Cache-Control header. As for POST, it is theoretically possible, but for which implementations do respect this... See https://stackoverflow.com/questions/626057/is-it-possible-to-cache-post-methods-in-http – Kaiido Sep 10 '18 at 03:19
0

You have to send cache-control header from your server to let browser cache your ajax request.

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...

You will see the status code 200, but if you check the Size column in chrome developer-tools you can see if it was loaded from cache.

chrome developer tools network panel

Munim Munna
  • 17,178
  • 6
  • 29
  • 58