I have a module that adds functionality to the front-end. The feature can be turned on or off via the configuration page of the module.
I pass the settings to the frontend in the HTML preprocess function using #attached
. Simplified, the code looks like this:
function my_module_preprocess_html(&$variables) {
$config = \Drupal::config('my_module.settings');
$settings = ['enabled' => $config->get('enabled')];
$variables['#attached']['drupalSettings']['my_module'] = $settings;
}
This approach is suggested here:
https://docs.acquia.com/tutorials/fast-track-drupal-8-coding/add-custom-variable-drupalsettings/
It works fine when logged in, but for anonymous users changing the setting from the module's configuration page does nothing until I clear caches (as, I assume, the drupalSettings variable is defined within the HTML that makes up the page)
So, my question:
- Is there a way to ensure the settings are fresh with each page load (without disabling the entire page cache, of course), or
- Should I refresh the cache whenever the module's configuration form is submitted? If so, what's the most efficient way to do that? (I've noticed a full cache clear is far slower on D8 than it was in D7)