[wp-trac] [WordPress Trac] #20558: allow wp_localize_script data to be added to existing objects

WordPress Trac wp-trac at lists.automattic.com
Fri Apr 27 16:44:04 UTC 2012


#20558: allow wp_localize_script data to be added to existing objects
-------------------------+-------------------------------------------------
 Reporter:  ryanve       |      Owner:
     Type:  enhancement  |     Status:  new
 Priority:  normal       |  Milestone:  Awaiting Review
Component:  Performance  |    Version:  3.3
 Severity:  minor        |   Keywords:  dev-feedback reporter-feedback 2nd-
                         |  opinion
-------------------------+-------------------------------------------------
 Re: WP_Scripts::localize() located in wp-includes/class.wp-scripts.php

 Currently when `WP_Scripts::localize()` handles the printing of
 wp_localize_script data to JavaScript, it starts the string with a `var`
 declaration, like this:

 {{{
 $script = "var $object_name = " . json_encode($l10n) . ';';
 }}}


 Because this is printed in the global scope, it becomes a global variable
 regardless of whether it's preceded by `var`. As far as JavaScript is
 concerned the above string would be equivalent to:

 {{{
 $script = $object_name . ' = ' . json_encode($l10n) . ';';
 }}}

 or

 {{{
 $script = 'this.' . $object_name . ' = ' . json_encode($l10n) .
 ';';
 }}}

 or

 {{{
 $script = 'window.' . $object_name . ' = ' . json_encode($l10n) .
 ';';
 }}}


 But I suppose it's possible thru hooks to make it so that the localization
 data prints outside of the global scope, in which case you might want the
 `var` to be there (if it we're wrapped in a closure). So I think the
 '''overall best solution''' would to check if the `$object_name` contains
 a period `.` character. If it does, omit the `var`. In other words, make
 it so that:

 {{{
 wp_localize_script('myplugin', 'myPluginData', $object )
 }}}

 would print:

 {{{
 var myPluginData = {...};
 }}}

 but that:

 {{{
 `wp_localize_script('myplugin', 'myPlugin.data', $object )`
 }}}

 would print:

 {{{
 myPlugin.data = {...};
 }}}

 By default the localization data runs before any enqueued scripts, in
 which case `myPlugin` would not yet be defined, but we should leave that
 for the JavaScript dev work out. My point is that the flexiblity should be
 there. Another route would be to apply a filter on that line but I don't
 think a filter is necessary if the above change is made.

-- 
Ticket URL: <http://core.trac.wordpress.org/ticket/20558>
WordPress Trac <http://core.trac.wordpress.org/>
WordPress blogging software


More information about the wp-trac mailing list