[wp-hackers] wp_localize_script - when should the JS var be available

J.D. Grimes jdg at codesymphony.co
Fri Apr 25 22:05:12 UTC 2014

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?


More information about the wp-hackers mailing list