WebWorkers - new Worker keeps requesting same script from server

Ad

On my server I have this logged:

GET /js/workers/one.js 200 2.509 ms - 828
GET /js/workers/one.js 304 1.593 ms - -
GET /js/workers/one.js 304 0.499 ms - -
GET /js/workers/one.js 304 0.464 ms - -
GET /js/workers/one.js 304 1.101 ms - -

(notice the 200, followed by 4 304s)

in my front-end code, there is this:

  var myWorker = new Worker('/js/workers/one.js');

why doesn't my front-end cache this file somehow? It keeps requesting the same file every time I call new Worker() ...

one way to solve it (maybe) might be to put the file in a <script> tag like so:

<script src="/js/workers/one.js"></script>

the problem with this, however, is that "importScripts" will not work

perhaps this will work?

if(typeof importScripts === 'function'){
    importScripts('https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react.js');
    importScripts('https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react-dom.js');
}

what is the best way to prevent new Worker() from re-requesting a file?

UPDATE:

If I put the js/workers.one.js file in a script tag like so

<script src="/js/workers/one"></script>

then the server does this:

GET /js/workers/one.js 304 0.521 ms - -
GET /js/workers/one.js 304 0.605 ms - -
GET /js/workers/one.js 304 0.289 ms - -
GET /js/workers/one.js 304 0.300 ms - -
GET /js/workers/one.js 304 0.347 ms - -

(notice the 5 304s)

so it's already loaded, (unlike before where there was one 200 response), but new Worker() keeps requesting it...

Ad

Answer

Ad

304 status code means that your browser does have the file cached actually and is explicitly allowed to reuse it by the server. The request is performed because the cached version is considered stale for some reason and must be validated by the server.

When serving the file you can explicitly indicate its freshness lifetime by adding some http headers in the response with the file data. You can add Expires header with the date/time after which the response is considered stale, e.g.:

Expires: Thu, 17 Dec 2015 16:00:00 GMT

With Cache-control header and max-age response directive you can indicate that the response is to be considered stale after its age is greater than the specified number of seconds:

Cache-Control: max-age=600
Ad
source: stackoverflow.com
Ad