Prevent files from caching
Last edit by:
Walter Davis
16 Apr, 2012
This simple example shows how we can prevent external files from caching in the browser by using MD5 hash codes.
Actions that create external resources such as CSS files can run into problems when the browser caches the file and displays old styles rather than the newly generated ones.
This simple example uses a terminal command to generate a unique MD5 checksum code of the file. This is appended to the file name as a query string when we reference the file in the source code.
For example;
<link rel="stylesheet" type="text/css" href="Resources/css-file.css?d417640cd18afc763744edb24f8fc97b">
This hash code will remain the same while the file stays unchanged allowing the file to be cached in the browser. As soon as the file changes a newly generated query string is added which will force the browser to see the file as unique and will load it again from source.
Below is a simple page Action that uses a common library to create a MD5 checksum for a file. Feel free to copy the library to use in your own Actions.
The only limitation of using this method is that AppleScript needs to be enabled for Actions (in Freeway’s preferences).
<library-action name="md5_cache_library">
<action-javascript>
function createHashTag(fileref){
if (fwParameters[fileref].fwHasFile){
var theFile = fwConvertFilePath(fwParameters[fileref].fwPathName);
var theCode = "md5 '" + theFile + "'";
var theResult = fwShellCommand(theCode);
theResult = theResult.slice(theResult.lastIndexOf("=")+2,theResult.lastIndexOf("\r"));
return theResult;
}
}
</action-javascript>
</library-action>
<page-action name="com.freewayactions.actions.preventcachingexample" title="Prevent Caching Example">
<action-appliesto applescript/>
<action-file name="myfile" title="Stylesheet">
<action-version version="1.00">
"Prevent Caching Example" action
Copyright © Tim Plumb 2012
</action-version>
<action-include name="md5_cache_library">
<action-javascript>
function fwAfterEndBody(){
var head = fwDocument.fwTags.fwFind("head");
if (head){
if (fwParameters["myfile"].fwHasFile){
var styleslink = head.fwAdd("link");
styleslink.rel = fwQuote("stylesheet");
styleslink.type = fwQuote("text/css");
styleslink.href = fwQuote(fwParameters["myfile"].fwValue.toString() + ("?"+createHashTag('myfile')));
var enclosing = styleslink.fwFindEnclosing();
enclosing.fwAddRawOpt("");
}
}
}
</action-javascript>
</page-action>
