Cache js files (and delete all after changing/saving content)

I can’t wrap my head around it.

I want to cache my generated javascript / or even css files, which are dynamically created depending on what snippets I include (e.g. one pager with different sections)

the optimal way would be using

  • timestamp / version (for cache refresh)
  • delete old files after page refresh

is there any way i can leverage the existing caching functions where these could be purged after changing though the panel?

function cacheScripts(){
    $page = page();
    $file = 'assets/js/pages/'.$page->uid().'.js';
    $asset = new Asset($file);
    return js($file);

(in this the generation is already cached with the cache driver after the page loaded for the first time)

In this example code, it’d generate a static script file which can then be included e.g.

  • …/home.js
  • …/about-us.js

ofc adding a modified handle would solve the ‘in cache’ problem, however this would generate many files over time which are not deleted after changing a page.

Ofc it would be possible to add Clearing out the Directory first, before the generation happens, i just wondered if there’s any build in tools available within the caching functions, to automatically do it.

Not sure i follow here, why not just use a Cachebuster like GitHub - schnti/kirby3-cachebuster

i could give it a try,…

but if i could solve that with a simple and straight-forward approach, i would skip using third party plugins … once in a while i encounter issues with plugins breaking after getting a newer update release.

there is a small bug with that one, it has an issue with auto loading but theres a PR fix that hasnt been acepted that fixes it

You could fork the plugin so you can keep on top of any issues. I know that plugin works fine with current release of Kirby, since i use it myself.

that’s my concern. the PR request has been open for quite some time. so i would have to rely on other developers :slight_smile:

can’t seem to get it working (installed with composer)

I adjusted my example code, which would do the job in case of file-cached driver … So after a change via panel on the next load of the content page, it’s clearing out the uid folder then saving the latest version as timestamp.js

function cacheScripts(){
    $page = page();
    $folder = 'assets/js/pages/'.$page->uid();
    $dir = Dir::read($folder);
    foreach($dir as $file){
        $asset = new Asset($folder.DS.$file);

    $file = $folder.DS.$page->modified().'.js';
    $asset = new Asset($file);
    return js($asset->url(),true);

// in Code / Template Bottom
<?= cacheScripts() ?>
// output == home/timestamp.js 
// <script async src="https://dev.test/assets/js/pages/home/1680174232.js"></script>

Did you add the rule to the htaccess file?


if you use the core pages cache and inline the generated js with <script> and <style> tags that would save you the hassle of managing the files.