Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between caching via Javascript vs setting HTTPResponse header in Server

On frontend I use AngularJS "$resource" for the GET request and on the Backend I use SpringMVC to expose my methods Restful way.

Now I want to cache only some of my GET requests. I noticed there are some ways to do that like using the $cacheFactory. Or something like:

 return {
   Things: $resource('url/to/:thing', {}, {
   list : {
   method : 'GET',
   cache : true
  }
 };

Please note that this could also be a simple ajax call with some cache parameters and not necessarly using the angularJS.

So instead of on the client using such an approach, I wonder it can be done on the server simply by Java setting the caching just in the Response header some thing like this:

response.setHeader("Cache-Control: max-age=2592000");

What are the difference of these two approaches? which approach should be used when?

P.S this question is NOT a server side caching vs client side caching question, I simply set the HTTPResponse header in the server that's all.

like image 543
Spring Avatar asked Oct 11 '13 13:10

Spring


1 Answers

I believe you are referring to caching at 2 different layers.

Angular's cache (see $cacheFactory) is an in-memory Javascript cache. The cache stores data in a Javascript Object. You have some control over them in the client. The cache will not persist, as in it will be gone once you navigate to another web page or refresh, unless you implement a custom cache that saves to local storage.

The Cache-Control parameter in the response controls the browser cache. You can't directly manipulate this cache from Javascript. But it will persist the data across sessions if you set the cache headers properly. It also lets any intermediate proxies, which may be serving multiple clients, know whether they can cache the request, reducing overall traffic more than the Javascript cache can.

As for which approach should be used when, I'd say in general rely on the browser cache since it's much lower level and persists across sessions. If you need more control over what gets cached that can only be reasonably obtained on the client-side, then use the Javascript cache. Or you could just enable both and get the benefits of both, and bear with the extra code maintenance/complexity.

like image 56
Yunchi Avatar answered Oct 21 '22 10:10

Yunchi