Drupal 8: Custom CSS & JS cache busting technique

A time may come when you need to implement your own cache busting technique to Drupal.

The solution is actually quite simple; we simply append a randomized version string to each file. That’s it!

All it requires is you tweaking your theme’s .theme file. Add the below code to the top of your .theme file.

use Drupal\Core\Asset\AttachedAssetsInterface;

Then add these 3 functions to your .theme file:

/**
* Function to generate a random string
*/

function randomString($length = 6) {
	$str = "";
	$characters = array_merge(range('A','Z'), range('a','z'), range('0','9'));
	$max = count($characters) - 1;
	for ($i = 0; $i < $length; $i++) {
		$rand = mt_rand(0, $max);
		$str .= $characters[$rand];
	}
	return $str;
}

/**
* Implements hook_css_alter().
*/

function jf_css_alter(&$css, AttachedAssetsInterface $assets){

    foreach ($css as &$file) {
        if ($file['type'] != 'external') {
            $file['type'] = 'external';
            $file['data'] = '/' . $file['data'] . '?v=' . randomString();
        }
    }

}

/**
* Implements hook_js_alter().
*/

function jf_js_alter(&$javascript, AttachedAssetsInterface $assets){

    foreach ($javascript as &$file) {
        if ($file['type'] != 'external') {
            $file['type'] = 'external';
            $file['data'] = '/' . $file['data'] . '?v=' . randomString();
        }
    }

}

That’s it! Simply save, clear your cache and check out your source, you should see something like ?v=g4ds3f added to each CSS and JS file

Drupal 8: Custom CSS & JS cache busting technique
Post Title
Drupal 8: Custom CSS & JS cache busting technique
Post Description
A time may come when you need to implement your own cache busting technique to Drupal.
Post Author

Posted: Thursday, December 19th, 2019

Leave a Reply

Your email address will not be published. Required fields are marked *


About Martin Grondein

Martin Grondein is a website developer Durban, South Africa, specializing in PHP/HTML5 Website development.