Make WordPress Core

Opened 15 months ago

Last modified 13 months ago

#58075 new defect (bug)

wp_enqueue_scripts action not firing at the right time with block themes

Reported by: wprj's profile wprj Owned by:
Milestone: Awaiting Review Priority: normal
Severity: major Version: 6.2
Component: Script Loader Keywords: needs-patch
Focuses: Cc:

Description (last modified by sabernhardt)

How to reproduce:

Use this piece of code somewhere in the (child) theme or a plugin

<?php
add_filter( 'the_content', function( $content ) {
        ob_start();
        var_dump( did_action( 'wp_enqueue_scripts' ) );
        $done = ob_get_clean();
        return $content . $done;
} );

It will print 0 despite being in the middle of processing the post content.

It cause problems for plugins that add inline JS (wp_add_inline_script) in the post content that are generated from plugin settings or a block attributes for instance.

Does not happen with any other theme

Change History (4)

#1 @sabernhardt
15 months ago

  • Description modified (diff)
  • Summary changed from `wp_enqueue_scripts` action not firing at the right time to Twenty Twenty-Three: wp_enqueue_scripts action not firing at the right time

#2 @wprj
15 months ago

@sabernhardt Seems to be somehow related to the site editor (/wp-admin/site-editor.php) as it also happens with Twenty Twenty-Two but not Twenty Twenty-One

#3 @sabernhardt
15 months ago

  • Component changed from Bundled Theme to Script Loader
  • Summary changed from Twenty Twenty-Three: wp_enqueue_scripts action not firing at the right time to wp_enqueue_scripts action not firing at the right time with block themes

I thought I had tried Twenty Twenty-Two yesterday, but today I have the same 0 result with that content filter in Twenty Twenty-Two, Twenty Twenty-Three, Course and EduBlock themes.

#4 @yashskukreja
13 months ago

@sabernhardt @wprj
I think this is happening because of the fact that all the blocks are rendered and resolved first.
As per the flow, all the blocks are resolved in locate_block_template() which sets up the block content. At this stage, the scripts aren't enqueued. This is the reason why when we are checking did_action() on the content, it shows 0.
locate_block_template() returns the wp-include/template-canvas.php which added the HTML markup on our block content with wp_head() (which enqueues the scripts).

Scripts do enqueue in the final template, which you can see by adding the following code in wp-include/template-canvas.php:

<?php echo $template_html; // phpcs:ignore WordPress.Security.EscapeOutput ?>

<?php echo 'enqueued - ' . did_action( 'wp_enqueue_scripts' ); // Add this line ?>

Note: See TracTickets for help on using tickets.