Make WordPress Core

Opened 2 months ago

Last modified 2 months ago

#59462 assigned enhancement

Blocks: Introduce a way to enqueue view scripts only when needed for interactivity

Reported by: gziolo's profile gziolo Owned by:
Milestone: 6.5 Priority: normal
Severity: normal Version: 6.4
Component: Editor Keywords:
Focuses: Cc:

Description

It's based on the discussion started by @felixarntz in https://github.com/WordPress/wordpress-develop/pull/5262#discussion_r1336258326 when reviewing the current handling for interactive blocks back ported from the Gutenberg plugin for WordPress 6.4 Beta 1.

As of today, the view scripts get enqueued during block rendering in WP_Block::render:

https://github.com/WordPress/wordpress-develop/blob/6a61084beca680a78ed581d035d76d592d4ef117/src/wp-includes/class-wp-block.php#L271-L274

The custom code used with all core blocks applies the optimization by ensuring that these view scripts are only listed for enqueuing when the block instance of a given type is going to need them. For example, in the Image block, the view script is only useful when the Lightbox feature is activated for the block. There can be multiple block instances of the same type, so the view script gets removed from the list when the functionality isn't used. However, as soon as any block instance needs it, it must be added and never removed.

The reason why we didn't go with wp_enqueue_script() and wp_dequeue_script() is that the script handle would still need to get removed from view_script_handles for the block type as it gets automatically registered through block.json and later enqueued in the code path shared in the snippet above. It would still have to be manually enqueued when it is needed.

In the long run, I hope we can develop some sort of automatic detection based on Interactivity API directives that would inform whether a view script is necessary for the block. It could even allow us to introduce new strategies that allow loading scripts based on some triggers like: when a user hovers over a UI element or when the UI element is visible on the screen.

Change History (1)

#1 @luisherranz
2 months ago

It could even allow us to introduce new strategies that allow loading scripts based on some triggers like: when a user hovers over a UI element or when the UI element is visible on the screen.

I started a discussion about lazy loading support a few months ago here:

https://github.com/WordPress/gutenberg/discussions/52723

I plan to work on all this after WP 6.4 is released.

Note: See TracTickets for help on using tickets.