Vitalii
Vitalii

Reputation: 11071

Set version of javascript file. Java EE + Tomcat

By adding updates to javascript and css I want to avoid to force users to press Ctrl+F5 to refresh cached js and css files.

Disabling cache is not a choise too.

For this I suppose to add version to js and css links like this

< link href="~/CSS/file.css?MY_VERSION" rel="stylesheet" />

Ideally version has to be something like build number of build date and time.
But how can I set this automatically?

I do not want to update this values at all jsp files manually after every update. So questions are

Upvotes: 0

Views: 1376

Answers (1)

Stijn Geukens
Stijn Geukens

Reputation: 15628

Yes, we do something similar (for image references in css files):

<plugin>
    <groupId>com.google.code.maven-replacer-plugin</groupId>
    <artifactId>maven-replacer-plugin</artifactId>
    <version>1.4.1</version>
    <executions>
        <execution>
            <id>anticache</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>replace</goal>
            </goals>
            <configuration>
                <includes>
                    <include>target/classes/**/*.css</include>
                </includes>
                <replacements>
                    <replacement>
                        <token>anti-cache=anti-cache-parameter</token>
                        <value>anti-cache=${maven.build.timestamp}</value>
                    </replacement>
                </replacements>
            </configuration>
        </execution>
    </executions>
</plugin>

Just check the file pattern to match your JS files and then in your JS files:

< link href="~/CSS/file.css#anti-cache=anti-cache-parameter" rel="stylesheet" />

Note that I don't use a request parameter (?) here but #. This is to avoid that the browser cache will be impacted since with a request parameter the browser cache will hang on to each version of the file. See also: Refresh image with a new one at the same url

Now, as said, we use this but it's not an ideal solution either but then I don't think an ideal solution exists.

Also see the behavior of caching in different browsers: https://github.com/podlipensky/RefreshButton

Upvotes: 2

Related Questions