I’m implementing a site that allows users to switch stylesheets (to show a high contrast version for people with vision impairments). The switcher essentially just changes the
<link>ref to whichever stylesheet is appropriate.
However, I just realised that this will lead to problems when I switch on caching (either using WP Supercache or W3 Total Cache) – as only one version of the page will be cached and thus displayed to the user.
Any thoughts on possible solutions?
I use W3TC, so these are approaches that I can come up with it for it:
Fragment caching to exclude that part of page, will reduce cache effectiveness overall.
Identify page with switched stylesheet by query argument, disable caching of such pages.
Identify page with switched stylesheet by URL endpoint, disable caching of such by mask.
Idea: If you enqueue the styles, use
filemtime() for the
version. If it finds changes to your previous stylesheet, caching will be prevented and a new stylesheet gets loaded.
Turns out the answer is fairly simple (at least for WP Supercache).
$wp_super_cache_late_init = 1;in
<!--dynamic-cached-content-->directive to wrap the content that should remain dynamic.
<!--dynamic-cached-content--><?php display_high_contrast_link(); ?><!-- display_high_contrast_link(); --><!--/dynamic-cached-content-->
As you can see, the dynamic content has been added twice – from the WP Supercache FAQ
The first code is executed when the page is cached, while the second chunk of code is executed when the cached page is served to the next visitor.