Discussion:
wp_localize_script - when should the JS var be available
J.D. Grimes
2014-04-25 22:05:12 UTC
Permalink
When making data available to a script using wp_locaize_script() is it safe to assume that the JS variable holding the data will be available when the file JS file is parsed/executed? Or is it only guaranteed to be available by the time the DOM is ready?

I ask because I noticed an "undefined variable ‘settings’” notice in the browser console. This (poorly named) variable is being added by a plugin using wp_localize_script(). When I check the page source, I see that the data is being output, but not until *after* the script tags in the head. I think WP usually outputs the data immediately above the script tag for the file that uses it, but in this case it isn’t (a caching plugin is being used which is probably the cause). I notice that none of the other scripts seem to be giving undefined variable notices though, likely because they don’t attempt to use their localized data until the DOM is ready . So I’m wondering who is doing it wrong. Is it wrong for the plugin to assume that the variable will be there when the file is parsed, or should the caching plugin (or whatever the culprit) not be moving the localized data below the scripts?

-J.D.
Eric Andrew Lewis
2014-04-26 17:25:42 UTC
Permalink
Any localized script has the data output directly preceding the related script element, via the print_extra_script() method in WP_Scripts (https://github.com/WordPress/WordPress/blob/master/wp-includes/class.wp-scripts.php#L127).

--
Eric Andrew Lewis
Post by J.D. Grimes
I ask because I noticed an "undefined variable ‘settings’” notice in the browser console. This (poorly named) variable is being added by a plugin using wp_localize_script(). When I check the page source, I see that the data is being output, but not until *after* the script tags in the head. I think WP usually outputs the data immediately above the script tag for the file that uses it, but in this case it isn’t (a caching plugin is being used which is probably the cause). I notice that none of the other scripts seem to be giving undefined variable notices though, likely because they don’t attempt to use their localized data until the DOM is ready . So I’m wondering who is doing it wrong. Is it wrong for the plugin to assume that the variable will be there when the file is parsed, or should the caching plugin (or whatever the culprit) not be moving the localized data below the scripts?
Loading...