Automatic Cache Buster

This is just a quick post to share a JavaScript snippet I came up with.

I’m currently working on a project with very aggressive server-side caching. Every requested URL is cached, so if I make any changes and want to see them, I have to tweak the query string to create a unique URL. Very tedious.

So I wrote a script that attaches a keydown listener to the window and listens for F5 or ctrl + r to be pressed. It intercepts the browser’s usual reload behavior, sticks a unique timestamp into the current URL’s query string, and requests that new URL instead. This sidesteps the server-side caching and lets me check rapid-fire changes much more quickly.

window.addEventListener('keydown', function(e) {
    if (e.keyCode === 116 || (e.ctrlKey && e.keyCode === 82)) { // f5 or ctrl + r
        // parse URL
        var split = window.location.href.split('#');
        var url = split[0];
        var hash = split[1];

        // set cache-busting query string param
        var pair = 'cachebuster=' + Date.now();
        if (url.indexOf('cachebuster=') > -1) {
            url = url.replace(/cachebuster=\d+/, pair);
        } else {
            url += (url.indexOf('?') > -1 ? '&' : '?') + pair;
        }

        // reassemble
        var final = url + (hash ? '#' + hash : '');
        window.location.href = final;

        e.preventDefault();
    }
});

The URL parsing isn’t 100% bullet-proof, but more than enough for my needs. I went ahead and created a GitHub repo in case I decide to take this thing further.

Hey, you reached the end!

Feel free to check out my other blog posts or subscribe to my RSS feed. You can also click a tag below to see related blog posts.