Aleš Sýkora / November 28, 2023 / 3 comments

Load Gutenberg Styles only if page has blocks

Post summary: Trying to speed up your site? You may want to disable Gutenberg block style libraries on pages and posts which doesn’t have any blocks. Add this code to your custom snippets and test it. It should disable loading of Gutenberg styles when not needed. It works with Oxygen Builder and Advanced scripts – I have…

Trying to speed up your site? You may want to disable Gutenberg block style libraries on pages and posts which doesn’t have any blocks. Add this code to your custom snippets and test it. It should disable loading of Gutenberg styles when not needed.

It works with Oxygen Builder and Advanced scripts – I have tested it on my sites.

/* Check if page uses blocks */
function is_gutenberg_page() {
		global $post;
		if ( function_exists( 'has_blocks' ) && has_blocks( $post->ID ) ) {
			return true;
		} else {
			return false;
		}
}
/* Remove Gutenberg stuff when no blocks being used. */
add_action( 'wp_enqueue_scripts', 'conditionally_load_gutenberg_styles' );
function conditionally_load_gutenberg_styles() {
	// if this is a Gutenberg, abort.
	if ( is_gutenberg_page() ) {
		return;
	}
    wp_dequeue_style( 'wp-block-library' );
    wp_dequeue_style( 'wp-block-library-theme' );
    wp_dequeue_style( 'wc-block-style' );
    wp_dequeue_style( 'wc-blocks-style' );
}

Advanced scripts example

If you want to use it with Advanced Scripts, you should create the script like you see on the image below:

Pagespeed insights – remove unused styles – Gutenberg

This script can help you maximize your pagespeed scores. If you don’t use Gutenberg editor, you may notice this:

Remove unused CSS WordPress block styles

After using this script the gutenberg styles are not loaded anymore.

Do you want more speedup tips? Let me know in the comments :).

Fuel my passion for writing with a beer🍺

Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻

3 comments

Share Your Thoughts