markjaquith / feedback

Ask @markjaquith anything!
42 stars 4 forks source link

wp_enqueue_script() vs add_action('wp_head') #9

Closed MickeyKay closed 10 years ago

MickeyKay commented 10 years ago

Can you speak to the advantages/disadvantages of including JS using both of these methods?

I typically use wp_enqueue_script(), however I'm working on a project in which my JS includes numerous PHP variables, and so it seems like hooking into wp_head would be a lot easier than using wp_localize_script().

I can see how this is risky if I'm including a commonly used script that might be re-registered by another plugin/theme, but are there other concerns? Thanks!

markjaquith commented 10 years ago

I would always encourage you to use wp_enqueue_script(). You get automatic dependency resolution, you allow other plugins to manipulate your script, and you enable easy concatenation and minification via plugins. What is okay, however, in my book, is using wp_head to do late printing of dynamic JS variables. Like, you might not determine the values until close to wp_head, so I think it's okay to hook in early there and print your JS values. Be sure to use esc_js().