Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
I tried setting headers:dnt and also max-age, but it has no effect. The #attached code is always cached.
Example snippet (change the text to see that the cache is not refreshing):
function mymodule_page_attachments(array &$page) {
$dnt = (!empty($_SERVER['HTTP_DNT'])) ? [] : ['headers:dnt'];
$page['#cache']['contexts'] = Cache::mergeContexts(isset($page['#cache']['contexts']) ? $page['#cache']['contexts'] : [], $dnt);
$page['#cache']['tags'] = Cache::mergeTags(isset($page['#cache']['tags']) ? $page['#cache']['tags'] : [], $config->getCacheTags());
$page['#cache']['max-age'] = 0;
$script = 'alert('This is a test.');';
$page['#attached']['html_head'][] = [
[
'#tag' => 'script',
'#value' => $script,
],
'mymodule_script',
];
}
How can I make the script dependend on a lot of rules? Best would be no cache at all.
Comments
Comment #1
hass CreditAttribution: hass commentedComment #2
dawehnerI would have expected that even does doesn't work.
Comment #3
hass CreditAttribution: hass commentedBedir has provided a patch to add the cache tags and this at least works. No idea why the rest does not. I need the rest for Google Analytics, too.
Comment #4
BerdirNo, you don't.
The anonymous page cache does not support cache contexts and doesn't respect max-age. By design.
Adding this would mean that you would completely break the page cache for the whole site. Obviously, that would be a very bad idea.
Again, the page cache is no different to Drupal 7, you had exactly the same problems there, you just didn't notice as it wasn't enabled in the tests.
Yes, smartcache is a different topic but that doesn't exist yet. That will respect contexts and it will work as long as you ensure that the relevant contexts are there. Which is a good reason to use condition plugins with context but a few things are still missing for that to properly work.
As I've told you multiple times and others told you as well in the smartcache issue. There is only one way to make the DNT header work when combined with page cache: You need to do it in JS.
Comment #5
hass CreditAttribution: hass commentedFabian said I can use headers:dnt and it does not require JS.
Comment #6
dawehnerWell, if your module does not support page_cache module, you could communicate that otherwise.
Comment #7
Wim LeersComment #11
Wim LeersComment #12
Wim Leershttps://www.drupal.org/project/cache_control_override implements this in contrib, see http://cgit.drupalcode.org/cache_control_override/tree/src/PageCache/Den....
Comment #15
bradjones1Duplicate of #2352009: [pp-3] Bubbling of elements' max-age to the page's headers and the page cache
Comment #16
dpiComment #17
DamienMcKenna