Thursday, September 1, 2016

How to Prevent Browser Caching of a CSS Stylesheet in WordPress

In this video guide, I explain (with a bit of help from my dog, who wanted attention) how to force browsers to load a CSS stylesheet from scratch on every page load. The purpose of this is to disable browser caching of that stylesheet, since in some situations outdated CSS styles can lead to a broken user experience.

Query Strings

The main point is that your browser will treat the following two files differently:

mysite.com/style.css

mysite.com/style.css?anything=goeshere

However, it's still the same file! Nothing about its contents has to change, and the query string ?anything=goeshere doesn't have to do anything. Just putting it there forces the browser to respect it, and to load the stylesheet from scratch if it hasn't seen that query string before.

Adding a Random Query String to a Stylesheet You Control

By default, WordPress adds query strings, but they don't change often. However, the video explains how to force the query string to change every page load, by making the query string a large random number. You'll want to change the code from this:

wp_enqueue_style( 'wpshout-style', get_stylesheet_uri() );

To this:

$rand = rand( 1, 99999999999 ); wp_enqueue_style( 'wpshout-style', get_stylesheet_uri(), '', $rand );

This is if the original has no third argument—if it does, leave it there as-is.

Adding a Random Query String to a Stylesheet You Don't Control

This is a bit trickier. You'll have to dequeue the original style, and requeue it yourself with the query string. You'll want to write this into a plugin, with the following as its body:

function wpshout_force_css_refresh() { wp_dequeue_style( '[STYLESHEET_SLUG]' ); $rand = rand( 0, 999999999999 ); wp_enqueue_style( '[STYLESHEET_SLUG]', [PERMALINK_TO_STYLESHEET], [STYLESHEET_DEPENDENCIES], $rand ); } add_action( 'wp_enqueue_scripts', 'wpshout_force_css_refresh' );

To find a stylesheet's slug, "View Source" and find the id of the stylesheet, then remove -css. The id of WPShout's main stylesheet is wpshout-style-css, and so its slug is wpshout-style.

If you need help knowing what to put into [PERMAINK_TO_STYLESHEET], view our article on the topic.

[STYLESHEET_DEPENDENCIES] should be either '' or whatever the stylesheet's listed dependencies are in the code that originally enqueues it.


Source: How to Prevent Browser Caching of a CSS Stylesheet in WordPress

No comments:

Post a Comment