Opened 4 months ago
Last modified 3 months ago
#63693 new defect (bug)
wp_should_load_block_assets_on_demand doing it wrong too early
| Reported by: |
|
Owned by: | |
|---|---|---|---|
| Milestone: | Awaiting Review | Priority: | normal |
| Severity: | normal | Version: | |
| Component: | Script Loader | Keywords: | |
| Focuses: | Cc: |
Description
wp_should_load_block_assets_on_demand() calls wp_is_rest_endpoint() which generally only works after parse_request hook (since that's where the constant gets defined) https://github.com/WordPress/wordpress-develop/blob/trunk/src/wp-includes/script-loader.php#L2644 since it will always return false before that hook.
The same thing also for wp_should_load_separate_core_block_assets() https://github.com/WordPress/wordpress-develop/blob/trunk/src/wp-includes/script-loader.php#L2609
However it's often called way too early, e.g. on "init" hook, e.g. in WooCommerce https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce/src/Blocks/BlockTypesController.php#L632 and https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce/src/Blocks/BlockTypesController.php#L633
Or in WP core itself, e.g. when calling wp_register_style( on "init", it will subsequently call wp_default_styles() and then the load block assets on demand function.
The same also in WP core register_block_type_from_metadata(, essentially all the stuff on init in "blocks" wp-includes, e.g. register_block_core_archives() on init
Or for example even in the file that's declaring those: https://github.com/WordPress/wordpress-develop/blob/trunk/src/wp-includes/script-loader.php#L1798
I guess that all those "init" registered block things should be moved to run later on "parse_request" (or "wp") hook? Or alternatively, remove the "wp_is_rest_endpoint()" check since at the point in time it's called on "init", it's not ready yet and always returns false.
Possibly add a "doing_it_wrong" in wp_is_serving_rest_request for ! did_action( 'parse_request' )
Should block registration/asset registration be moved later, e.g. on parse_request or wp, so that the rest context is actually known?
Or instead, should the wp_is_rest_endpoint() check be adjusted/removed in these functions, since it can’t return meaningful results that early anyway?