Make WordPress Core


Ignore:
Timestamp:
10/14/2025 12:10:31 AM (12 months ago)
Author:
westonruter
Message:

Editor: Avoid enqueueing assets for blocks which do not render content.

This change prevents scripts, styles, and script modules from being enqueued for blocks that do not render any HTML content. This is common for hidden blocks or blocks like the Featured Image block when no image is present. This change reduces the amount of unused CSS and JavaScript on a page, improving performance.

A new filter, enqueue_empty_block_content_assets, is introduced to allow developers to override this behavior and enqueue assets for empty blocks if needed.

The implementation involves capturing the asset queues before and after a block is rendered. The newly enqueued assets are only merged if the block's rendered content is not empty. This is done recursively for nested blocks to ensure that assets for inner blocks are also not enqueued if a parent block is hidden.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/9213.

Props westonruter, aristath, peterwilsoncc, gziolo, krupajnanda, dd32, jorbin.
See #50328.
Fixes #63676.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/blocks/editor.php

    r60719 r60930  
    3232                global $post_ID;
    3333                $post_ID = 1;
     34
     35                global $wp_scripts, $wp_styles;
     36                $this->original_wp_scripts = $wp_scripts;
     37                $this->original_wp_styles  = $wp_styles;
     38                $wp_scripts                = null;
     39                $wp_styles                 = null;
     40                wp_scripts();
     41                wp_styles();
    3442        }
    3543
    3644        public function tear_down() {
     45                global $wp_scripts, $wp_styles;
     46                $wp_scripts = $this->original_wp_scripts;
     47                $wp_styles  = $this->original_wp_styles;
     48
    3749                /** @var WP_REST_Server $wp_rest_server */
    3850                global $wp_rest_server;
    … …  
    4254                parent::tear_down();
    4355        }
     56
     57        /**
     58         * @var WP_Scripts|null
     59         */
     60        protected $original_wp_scripts;
     61
     62        /**
     63         * @var WP_Styles|null
     64         */
     65        protected $original_wp_styles;
    4466
    4567        public function filter_set_block_categories_post( $block_categories, $post ) {
Note: See TracChangeset for help on using the changeset viewer.