Tuesday 27 March 2018

Prevent CSS and Javascript caching

Quite often, during the early days of a web site's/application's life, a developer can make minor corrections to JavaScript and CSS, whether to correct an issue, or in response to customer feedback.
Unfortunately, nearly all browsers cache these files to facilitate faster loading times during a revisit to a site. Whilst this is desirable for normal day to day use, it can be a developer's nightmare as they have to let the users, if known, know to refresh their cache, or if unknown, find another way to communicate this message.
However, there is a way around this.

The answer is known as using a phantom query string. Like requests for HTML pages, it is possible to append a query string to the references of the scripts and stylesheets. If these are unique on each call, then the file is reloaded from the internet, rather than the cache.
To accomplish this, it is as easy as adding a date and time stamp to the query part of the reference:
e.g.

    <script src="Scripts/script.js?636577391632578321"></script>
    <link href="Styles/style.css?636577391632578321" rel="stylesheet" />

If this date and time stamp is refreshed on each page load, then we can ensure that the file is also refreshed.
To accomplish this in PHP, we can use code like this:

    <link href="Styles/style.css?<?php echo time(); ?>" rel="stylesheet" />

Whereas in ASP/MVC, this will accomplish a similar task:

    <link href="Styles/style.css?@DateTime.Now.Ticks" rel="stylesheet" />

Use the same technique for JavaScript files.

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. That's actually pretty clever; good post!

    ReplyDelete