Make WordPress Core

Opened 6 weeks ago

Closed 6 weeks ago

Last modified 2 weeks ago

#61510 closed feature request (fixed)

Script Modules: Add mechanism to pass data from server to client

Reported by: jonsurrell's profile jonsurrell Owned by: jonsurrell's profile jonsurrell
Milestone: 6.7 Priority: normal
Severity: normal Version: 6.5
Component: Script Loader Keywords: has-patch has-unit-tests needs-dev-note
Focuses: javascript Cc:

Description

One useful feature available to Scripts that Script Modules do not support is a way for the server to send data to the client with the page. Scripts typically do this with wp_add_inline_script.

Proposal: Server to client data sharing for Script Modules proposes a mechanism for Script Modules to fill this need.

Part of #60647.

Change History (6)

#1 @jonsurrell
6 weeks ago

  • Component changed from General to Script Loader

This ticket was mentioned in PR #6682 on WordPress/wordpress-develop by @jonsurrell.


6 weeks ago
#2

  • Keywords has-patch has-unit-tests added

Add the print_script_module_data function to the WP_Script_Modules class.

Register hooks to call this function on wp_footer and admin_print_footer_scripts.

See the Make/Core Proposal and the PR in Gutenberg. In summary (from the proposal):

  • A new filter runs for each Script Module that is enqueued or in the dependency graph. This filter allows arbitrary data to be associated with a given Script Module and added to the rendered page.
  • Script Module data is embedded in the page as JSON in a <script type="application/json"> tag.
  • Script Modules are responsible for reading the data and performing their own initialization.

The new filter is "script_module_data_{$module_id}". It should accept and return an array that will be serialized in page HTML (if it is not empty):

add_filter(
        'script_module_data_myModuleID',
        function ( array $data ): array {
                $data['some-data-here'] = 'the client can read this on page load';
                return $data;
        }
);

#6683 includes an example of usage in for Core Script Modules.

Closes #6433 (superseded).

Trac ticket: https://core.trac.wordpress.org/ticket/61510

#4 @Bernhard Reiter
6 weeks ago

  • Resolution set to fixed
  • Status changed from assigned to closed

Fixed by [58579].

#5 @Bernhard Reiter
6 weeks ago

  • Milestone changed from Awaiting Review to 6.7

#6 @gziolo
2 weeks ago

  • Keywords needs-dev-note added
Note: See TracTickets for help on using tickets.