13
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CSSやJSのキャッシュ対策をGruntで行う

Posted at

目的

システムをアップデート時にCSSやJavascriptを更新していると,ブラウザのキャッシュが効いていて思った挙動にならなく困ったりします.
対策としては下記のようにCSS, JSのsrcにビルド時のタイムスタンプなどをQueryStringとして設定して強制的にリクエストを呼ばせます.

<link href="/css/main.css?rel=20141020" rel="stylesheet" type="text/css"/>

QueryStringをビルド時に動的につける方法は様々あるのですが,今回はGruntを使ってやってみました.

方法

grunt-cache-breakerといういい感じにQueryStringを追加してくれるPluginがあるので,使います.

Gruntfile.js

var moment = (require('moment'))();

module.exports = function (grunt) {
 
  var timestamp = 'None';
 
  grunt.initConfig({
    cachebreaker: {
      dist: {
        options: {
            match: [
              '.css',
              '.js'
            ],
            replacement: function () {
              return moment.format('YYYYMMDD');
            }
        },
        files: {
          src: [
            'build/**/WEB-INF/view/**/*.jsp'
          ]
        }
      }
    }
  });
 
  grunt.loadNpmTasks('grunt-cache-breaker');
 
  grunt.task.registerTask('default', ['cachebreaker:dist']);
};

package.json

{
  "name": "package",
  "version": "0.0.1",
  "devDependencies": {
    "grunt": "^0.4.5",
    "moment": "^2.8.3",
    "grunt-cache-breaker": "^1.0.1"
  }
}

使い方

$ npm install
$ grunt
13
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?