I encountered a similar problem and found another way to override entire stylesheets. It's quite straightforward.
I used this method on a theme that included a large CSS library file that also referenced other unoptimised assets. The whole thing was terrible for performance but the site still depended on some of its functionality.
The solution was to look through the plugin code and/or the HTML output to find the $handle
parameter passed to wp_register_style()
(or wp_enqueue_style()
), then register using that same handle. You do this by attaching to the same hook with a lower priority, or an earlier hook, than the one in which the original is registered. You register but do not enqueue your own version. This causes the original's registration to fail, but it should still enqueue yours because of the same handle.
To demonstrate, the theme registers the problematic style in a setup class:
public function __construct()
{
...
add_action('wp_enqueue_scripts', [$this, 'queueStyles']);
...
}
...
public function queueStyles()
{
...
wp_register_style(
'slow-lib',
get_theme_file_uri('css/slow.css'),
[],
'2.7.3'
);
wp_enqueue_style('slow-lib');
...
}
This produces output like so:
<link rel='stylesheet' id='slow-lib-css' href='https://simple.example/wp-content/themes/some-theme/css/slow.css?ver=2.7.3' media='all' />
In a basic custom plugin, I have optimised versions of the the assets (images, etc.) and refer to them in my own file. I then usurp the registration:
add_action(
'wp_enqueue_scripts',
function() {
# can add extra conditionals here if you need to make exceptions where the original should load
wp_register_style(
'slow-lib', # same handle
plugin_dir_url(__FILE__) . 'fast.css',
[], # same as original $deps parameter
'2.7.3' # anything, but best to keep track of which version you modified
);
},
-10, # lower priority than theme
0
);
The output changes to this:
<link rel='stylesheet' id='slow-lib-css' href='https://simple.example/wp-content/plugins/my-plugin/fast.css?ver=2.7.3' media='all' />
The original files are never loaded, but the replacements appear in the same place and satisfy the same dependencies. You can use any URL in your registration, including externally hosted files.