![]() |
|
Tutorial Catch-all cache buster script - Printable Version +- Sinisterly (https://sinister.ly) +-- Forum: Design (https://sinister.ly/Forum-Design) +--- Forum: Web Design (https://sinister.ly/Forum-Web-Design) +--- Thread: Tutorial Catch-all cache buster script (/Thread-Tutorial-Catch-all-cache-buster-script) |
Catch-all cache buster script - Inori - 02-01-2017 This is a super quick method I whipped up while working on one of my current projects that tricks the browser into thinking it's loading a different script file every time you visit the page, and thus eliminates the need to constantly clear your cache to get the right revision of the script to load. It isn't a super impressive piece of code, but it's saved me a ton of time so far. Code: <!-- put this right before the body closing tag (</body>) -->
<script>
// wait for the DOM to load completely
document.addEventListener('DOMContentLoaded',function(){
var scripts=['/file1.js','/file2.js'], // script files to load
stamp=Date.now(); // current timestamp
scripts.forEach(function(script){
// create a new <script></script> tag
var newTag=document.createElement('script');
// set the new tag's src attribute to the file + a dummy query
// string (this is what fools the browser)
newTag.setAttribute('src',script+'?nocache='+stamp);
// append the new tag to the body (below this script)
document.body.appendChild(newTag);
});
});
</script> |