Make WordPress Core

Changes between Initial Version and Version 15 of Ticket #58873


Ignore:
Timestamp:
08/20/2026 04:31:36 PM (8 weeks ago)
Author:
jonsurrell
Comment:

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #58873

    • Property Milestone Awaiting Review → Future Release
    • Property Status new → reopened
    • Property Keywords has-patch has-unit-tests added
    • Property Focuses javascript performance added
    • Property Summary Add function to pass variables to scripts → Script Loader: Add a filter to pass data from PHP to classic scripts
  • Ticket #58873 – Description

    initial v15  
     1
     2This 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
     4Script 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
     8Add 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
     10Follow the Script Modules implementation in `WP_Script_Modules::print_script_module_data()`, including its JSON encoding flags and charset handling.
     11
     12Ready for development. See the linked PRs.
     13
     14Filter 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
    123Since WordPress 5.7 using `wp_localize_scripts` to pass variables to registered scripts throws a `_doing_it_wrong` notice.
    224