Adding version to JavaScript and CSS Resources via JSP/JSTL
Browsers usually cache static resources like JavaScript and CSS so that downloads are reduced the next time the same website is visited.However, if the JavaScript or CSS gets updated in the server, the browser will still be using an outdated copy of the resource. This could lead to unexpected behavior.
This can be addressed by including a version to the resource name and incrementing the value every time an update is released (ex: /my-styles-v2.css). An easier alternative is to use a query parameter that indicates the resource version (ex: /my-styles.css?version=2). On either solution, HTML pages that link to the resources need to be updated whenever a resource version changes -- this can be difficult to maintain especially if there are many resources that constantly change.
There are tools that automate this process and are usually incorporated into the build process. The solution I'm going to demonstrate will address the issue without adding an extra build step.
Note: This example is specific to Java web applications using JSTL.
The first step is to add an application-level configuration that holds the current version of the static resources. This comes as a context parameter in web.xml:
<web-app> ... <!-- Indicates the CSS and JS versions --> <context-param> <param-name>resourceVersion</param-name> <param-value>1</param-value> </context-param> ... </web-app>Lines 6 and 7 indicate the value of the resource version and should be incremented before every release.
The next step is to update the JSPs that link to the resources and format the resource URLs to include the version number.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <c:url value="/resources/css/my-styles.css" var="myCss"> <c:param name="version" value="${initParam.resourceVersion}" /> </c:url> <c:url value="/resources/js/my-scripts.js" var="myJavaScript"> <c:param name="version" value="${initParam.resourceVersion}" /> </c:url> ... <!DOCTYPE html> <html lang="en"> <head> ... <link rel="stylesheet" href="${myCss}" type="text/css" /> ... </head> <body> ... <script src="${myJavaScript}"></script> </body> </html>Lines 2-7 declare URL variables that include "version" as a query parameter. Note that context parameters are accessible from JSTL via ${initParam}.
Lines 13 and 18 uses the variables to render the URLs.
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment