DEV Community

·ſ
·ſ

Posted on • Originally published at blog.julien-maury.dev

Optimize WordPress frontend assets

You need WordPress 5.8 at least and the new editor (Gutenberg) to enjoy this snippet.

I stumbled upon an interesting WordPress filter recently. The default value is false, but if you set it to true, it will skip styles you probably don't need:

function wp_enqueue_registered_block_scripts_and_styles() {
    global $current_screen;

    if ( wp_should_load_separate_core_block_assets() ) {
        return;
    }
Enter fullscreen mode Exit fullscreen mode
$path   = "/wp-includes/css/dist/$package/style$suffix.css";

    if ( 'block-library' === $package && wp_should_load_separate_core_block_assets() ) {
        $path = "/wp-includes/css/dist/$package/common$suffix.css";
    }
Enter fullscreen mode Exit fullscreen mode

Source: core WordPress - /wp-includes/script-loader.php.

If you don't need to load core styles and scripts everywhere, you can add the following code as a must-use plugin (~ special plugin that cannot be deactivated or deleted), for example, /wp-content/mu-plugins/optimize-core-block-assets.php:

<?php
/**
 * Plugin name: Optimize core block assets
 * Version: 1.0
 */
add_filter( 
    "should_load_separate_core_block_assets", 
    "__return_true" 
);
Enter fullscreen mode Exit fullscreen mode

To deeply understand what it does, please read this great answer

The only thing that bothers me is the filter's name, which I find a little confusing. I had some difficulties in understanding what the function and the filter do.

The following ticket explains what I'm saying: #53505

Anyway, it might improve the overall performance and allow you to tweak styles more conveniently. Be careful, though, and ensure it does not trigger any bug in your case.

Discussion (0)