JavaScript LogoUse the Date() constructor to create a unique query string; ensure each GET request is not cached

The other day, I was working with a customer whose iPad app was consuming an HTML page.
I was making changes to the CSS, yet was not seeing them in the iPad app. I kept adding a new query string to the URL of the CSS file, which forced the iPad app to download the updated CSS file. So, growing a little tired of changing the URL to the CSS element, I wrote a little cache buster script, and that was the end of the fiddling around.

This is very easy to do, so let’s look at an example.

Example # 1

In this example, we instantiate the Date() constructor, and get a reference to the time. Since this number is incremented by one, it will always be unique. We then create a new element, and set the required attributes: “rel”, “type” and “href”. The href has a query string that includes a reference to the time, so we have a GET request that is essentially different from the last one we made, and the next one we make will be different from this one, and so on.

Run this in your JavaScript console, and as long as you have a file name “style.css” in the same directory as your HTML file, you will see a new element appended to the <head> element. You can, of course, take the same approach with any resource that requires a web address such as a JavaScript file, an image, and so on.

Cache busting can ensure that often-changing files such as CSS and JavaScript always get downloaded by the client’s browser (i.e. never cached). It’s just a simple technique, but it can keep you from pulling your hair out.

Helpful Links for the subjet of cache busting

One Comment

Comments are closed.