How do you avoid caching during development?

Is there a simple way do prevent all caching when testing the appearance of changes to the site? I use WP Super Cache. I can delete its cache using the option provided, delete the cache for my browser, and still some changes to css or widgets do not refresh. I try other work-arounds like switching browsers or computers, but there must be a more stream-lined workflow where I can ensure I’m viewing the changes I made and not some cached earlier format? What’s the best solution for this?

10

Add the filemtime() of your stylesheet as version parameter. Lets say, your default stylesheet is in css/default.css and css/default.min.css (not style.css). When we register a stylesheet on wp_loaded (not init), we can pass a version as fourth parameter. That will be the last modified time and therefore change every time we change the file.

$min    = WP_DEBUG ? '': '.min';
$file   = "/css/default$min.css";
$url    = get_template_directory_uri() . $file;
$path   = get_template_directory() . $file;
$handle = get_stylesheet() . '-default';

// Overridden?
if ( is_child_theme() && is_readable( get_stylesheet_directory() . $file ) )
{
    $url  = get_stylesheet_directory_uri() . $file;
    $path = get_stylesheet_directory()     . $file;
}

$modified = filemtime( $path );

add_action( 'wp_loaded', function() use ( $handle, $url, $modified ) {
    wp_register_style( $handle, $url, [], $modified );
});

add_action( 'wp_enqueue_scripts', function() use ( $handle ) {
    wp_enqueue_style( $handle );
});

If you are using Node.js and Grunt, I strongly recommend Browsersync. It will watch your files and update them instantly whenever they change. It can also synchronize the scrolling position, form submissions and more across multiple open browsers. Very cool.

Leave a Comment