Force CSS and JS cache clean

Asked

Viewed 465 times

6

I work with a server. Whenever I change my CSS/JS and upload to the server, it does not directly change the version of my file, it is cached. I mean, I always have to clear the cache and then see the change I just made, which takes a lot of time. Is there any command or information in the file that I can force it to always clear the cache?

I need a solution with PHP

2 answers

2


Opa, this is very easy to solve, makes a simple function in php that always add a parameter at the end of your file, can use Rand

function getFileHash($file) {
        //Gera número aleatório para a versão
        return $file . '?v=' . rand(10000, 1000000000000);
    }
  • 1

    This would generate a filename for each request and cause it to be cached multiple versions of the same file. If the goal is just to disable the cache, this should be done by properly configuring the server. To want to circumvent by adding a random number is gambiarra. This can be done when you actually have control of the version of the file and it changes only when there are changes.

  • @Woss had never thought of it that way. Thanks for the comment in cases where cache is not necessary I will do so.

1

Using PHP makes it very simple, you can create a versioning variable and call it in the query string of the files. For example:

  1. Create a variable in a config.php file:
<?php
define(“Version”, “1”);
?>
  1. Apply the variable in the query strings of the file call
<link  rel=”stylesheet” href=”/style.css?v=<?php echo Version; ?>” type=”text/css” />
<script type=”text/javascript” src=”/javascript.js?v=<?php echo Version; ?>“></script>

This way whenever changing this variable the browser will recognize that it is a new file and will not give the problem with the cache.


If you do not want, for some reason, to work with this form of versioning, you can also oblige the browser to always download the files at each access:

<link  rel=”stylesheet” href=”/style.css?<?php echo time(); ?>” type=”text/css” />
<script type=”text/javascript” src=”/javascript.js?<?php echo time(); ?>“></script>

But this approach can hinder a little the loading of the site if the files are heavy and disturb the user experience that access frequently, by having this delay to download all the files always to display a page that he had already entered.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.