| | 1 | |
| | 2 | This ticket began as a request for a function to replace `wp_localize_script()`. The discussion rejected that. `wp_localize_script()` is for translations and casts values to strings (#25280). `wp_add_inline_script()` works but means writing JavaScript in PHP strings, adds a blocking script, and uses a global variable. |
| | 3 | |
| | 4 | Script Modules already have a better pattern: the `script_module_data_{$module_id}` filter. Returned data is printed as JSON in a `<script type="application/json">` tag, and the module reads it when it needs it. The browser does not run it as a script, and no global is needed. Converting the emoji loader to this pattern ([60899]) improved LCP by more than 5% on a low-end mobile device. |
| | 5 | |
| | 6 | == Proposal == |
| | 7 | |
| | 8 | Add the same filter to `WP_Scripts`. Before printing a script's localized data, translations, and inline scripts, apply a `script_data_{$handle}` filter. If it returns a non-empty array, print it as a JSON script tag with an ID the script can look up, such as `wp-script-data-{$handle}`. |
| | 9 | |
| | 10 | Follow the Script Modules implementation in `WP_Script_Modules::print_script_module_data()`, including its JSON encoding flags and charset handling. |
| | 11 | |
| | 12 | Ready for development. See the linked PRs. |
| | 13 | |
| | 14 | Filter name is still open between the two PRs (script_data_ vs script_client_data_); I used script_data_ since that's what comment:4 says. Swap it if you've decided otherwise. |
| | 15 | |
| | 16 | ----- |
| | 17 | |
| | 18 | **Original title:** Add function to pass variables to scripts |
| | 19 | |
| | 20 | |
| | 21 | **Original description:** |
| | 22 | |