Refresh JS and CSS, only when logged in

Sometimes the JS and CSS are cached in the browser. When developing that can be a bad thing.

Solution

Here is a solution, adding a get variable with timestamp. Then the browser is forced to refresh. It only refresh if the user is logged in to the panel.

<?php $refresh = r( $site->user(), '?refresh=' . time() ); ?>
<?php echo css('assets/css/style.css' . $refresh ) ?>
<?php echo js('assets/js/custom-dist.js' . $refresh ) ?>

With Kirby this code is tiny.

1 Like

Or use the Kirby Cachebuster Plugin, so it works automatically when you use css() and js()?

I like that your solution is tiny and simple though!

Thank you for the info!

I just can’t like the Cachebuster Plugin.

  • 47 lines of code!? My code for the refresh-part is 1 line.
  • Cachebuster requires to modify the htaccess which is an extra thing.

It’s however nice to not needing that 1 line extra in the template, but that could be solved like this…

<?php echo css('assets/css/style.css' . refresh() ) ?>
<?php echo js('assets/js/custom-dist.js' . refresh() ) ?>

…and have that 1 line as a function in a plugin folder.

Suggestion

The perfect way would probably be to filter the output of the functions css() and js(), but I guess Kirby doesn’t have that kind of hooks just yet.

A little update on this. I still use it on my site. I enhanced it to make the template less bloated by moving the code to a plugin.

Refresh CSS

<?php echo css('assets/css/style.css' . refresh() ) ?>

Refresh JS

<?php echo js('assets/js/custom-dist.js' . refresh() ) ?>

As a plugin

Add a plugin to /plugins/refresh/refresh.php with this code:

<?php
function refresh() {
    return r( site()->user(), '?refresh=' . time() );
}

Disadvantage: Every non-logged in user will always get the same file, and you can’t refresh them, because you only include the parameter for logged in users.
I still think that your solution is great because of its simplicity and the low amount of code required.

PS:

Actually Kirby does have a solution for that. Not hooks though, but handlers, but it works quite similar. See the Cachebuster plugin for an example.