notabucketofspam / html-cache-bust

Add hashes to CSS and JS file names and update their references in HTML documents

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

html-cache-bust

Add hashes to CSS and JS file names and update their references in HTML documents.


Place the shell script into the same directory as htmldir and cssjsdir folders; adjust the variables to whatever actual names are in use. Currently it only supports relative paths to these two folders with respect to the script file.

However, it uses absolute paths in each HTML file with respect to htmldir, so that on the server itself each reference begins with / (i.e. server root). Because of this, the directory tree of cssjsdir must match that of htmldir.

Basic overview of how it works:

  1. #!/bin/sh
    • setup shell
  2. export cssjsdir="css-js"
    • set relative path of the folder containing CSS and JS subfolders with source files in them
  3. export htmldir="html"
    • set relative path of the folder containing HTML files
  4. export shorthash=0
    • if true, file names will only include the first eight characters of the
  5. find "./""$cssjsdir" -type f \( -name '*.js' -o -name '*.css' \) -exec sh -c '
  6. for file do
    • find all files in cssjsdir folder and subfolders that are CSS or JS and exec below contents on the output
  7. fdir=$(dirname "$file" | cut -c 3-65535 | sed s,"$cssjsdir""/",,g)
  8. fname=$(basename "$file" | cut -d "." -f 1)
  9. fext=$(basename "$file" | cut -d "." -f 2)
    • respectively gets the path (relative), name, and extension of current file
  10. fhashfull=$(sha256sum "$file" | cut -d " " -f 1)
    • generate SHA2 of current file
  11. if [ "$shorthash" -eq 1 ]; then
  12. fhash=$(echo "$fhashfull" | cut -c 1-8)
  13. else
  14. fhash="$fhashfull"
  15. fi
    • optionally trim the hash length
  16. fpathfull="/""$fdir""/""$fname"-"$fhash"."$fext"
  17. echo "$fpathfull"
    • form path and name for the new file
  18. mkdir -p "$htmldir"/"$fdir"
  19. rm "$htmldir"/"$fdir"/"$fname"*"$fext"
  20. cat "$file" > "$htmldir"/"$fdir"/"$fname"-"$fhash"."$fext"
    • remove the existing file from htmldir and replace it with the new one
  21. for html in $(find ./"$htmldir" -type f \( -name "*.html" \)); do
    • find all HTML files in htmldir
  22. sed -i s,"/""$fdir""/""$fname".*"$fext","$fpathfull",g "$html"
    • replace every reference to the current file with the new file
  23. done
  24. done
    • end the for loops
  25. ' exec-sh {} +
    • end of exec command
  26. (\n)
    • newline at EOF because git yells at me otherwise

Source thread for the find / exec combo

About

Add hashes to CSS and JS file names and update their references in HTML documents


Languages

Language:JavaScript 71.2%Language:Shell 13.7%Language:HTML 13.3%Language:CSS 1.8%