cache-control mechanism for yeoman (angular+node) application.

24 views
Skip to first unread message

ashu anhad

unread,
Nov 18, 2015, 4:42:47 PM11/18/15
to nodejs


I have been struggling with a problem to manage and control cache for my one page application with multiple internal routing. I have used yeoman as a scaffolding tool for my application & Heroku is my server. I want to enable cache for images, java script, and html of my application, but if I make some changes in any of my files it should automatically reflect when the end user requests the page on that route again rather than rendering a cached copy of that page.

I wrote a code in my web.js as:

app.use(function noCache(req, res, next) {
    res.header("Cache-Control", "no-cache, no-store, must-revalidate"); 
    res.header("Pragma", "no-cache"); 
    res.header("Expires",0); 
    next(); 
});

This code stops all the caching of the application in any browser. But this affects my website's speed as each request from the end user renders all data(images, HTML, JS) from the server weather it is modified or not.

I have internal routing in my application's app.js file which renders various pages on different URL request as follows:

app.config(function ($routeProvider) {
    $routeProvider
      .when('/main', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
      })
     .otherwise({
        redirectTo: '/main'
      });
});

So what should I code for enabling caching for my application which should render a fresh copy of a modified file and cached copy of the unmodified files and images.
So can someone help to get me a workaround for my issue.

Thanks.

Zlatko

unread,
Nov 19, 2015, 5:21:29 AM11/19/15
to nodejs
There are a few ways to do that, but I find adding gulp-rev build step the easiest to think about.

It's a build step, meaning it's done before you commit your changes and it gives you a hash of the file content. So if you change even a single character, you have a new hash for that file.

So how does that help? Well, include the hash on the filename, maybe just as a query string, for that resource.

E.g. You have file1.js, with hash asdf123, you include that file as src="file1-asdf123.js", or "file1.js?rev=asdf123". Now, the client will cache that for r. And if you change the file, it has a new hash, and therefore a new name, so the browser will fetch it again fresh.

There are other solutions similar to that, like using the file timestamp, gut hash num, manually bumping the number etc, but the mechanism is essentially the same. If bleeding edge is fine by you, you can also take a look at service workers, it's in all the headlines lately, but implemented in only a fraction of browsers. Similar to that, there are other ways to do this, but I don't think they're worth mentioning here or I don't know enough about them to comment.

As said, gulp-rev was always good enough for me.
Reply all
Reply to author
Forward
0 new messages