How to prevent Cache in Javascript library file

Cache in JavaScript is a unique string which is appended in URL in the from of query string. It is not read generally server side and used purely to form of unique URL.

For Ex-maple: /Scripts/foo.js?v=1

This is often used on client side files such as JavaScript, CSS and Images in order to forces a browser/cache-system is retrieve the latest version of a file and its source. Its purposes so that web page doesn’t have to download the files every time the page is refreshed.
As developer, if you can make a change any of those files, you need ensure client will download the latest version. The cache-buster query string can updated so that browser doesn’t recognize the file in its cache and downloads a new version.

1)Static cache-buster:

When file updated, all references to the file could be manually updated to increasing a version number add with file name.

For example:

<script type="text/javascript" src="/Scripts/foo.js?v=1"></script>

<script type="text/javascript" src="/Scripts/foo.js?v=2"></script>

However this is not a clean solutions because this task will have to be carried out every time the file is updated. And in cases where its forgotten. Browsers will potentially still use an older version of the file.

2)Date/Time Cache-buster:

Current date/time could be append to reference with file name. This point browsers caching files at all.

Example:

<?php echo $date = date("Y-m-d"); ?>
<script type="text/javascript" src="/Scripts/foo.js?v=<?php echo $date; ?>"></script>

3) Software version :

Another method use of cache-bustin is use the software versions of the application. This ensure that a new version for the application is deployed.
see example:

<script type="text/javascript" src="/Scripts/foo.js?v=2014.9.25.75285"></script>

Any method you can choose, cache-busting is a great way to ensure your clients are using the most.

Read Also :-

Understanding CSS Variables [With Examples]

Understanding PHP 8 Named Arguments

Also Visit:-

https://inimisttech.com/

Leave a Reply