wp_enqueue_script in action hook wp_print_scripts

In the WordPress documentation page for the function wp_enqueue_script, it is clearly written:

Note: This function will not work if it is called from a wp_head action, as the tags are output before wp_head runs. Instead, call wp_enqueue_script from an init action function (to load it in all pages), template_redirect (to load it in public pages only), or admin_print_scripts (for admin pages only). Do not use wp_print_scripts (see here for an explanation).

Read More

Do not use wp_print_scripts action is what I want to highlight, but do a simple google search on “How to include Javscript in WordPress”. You will find most of examples are using wp_print_scripts action to call wp_enqueue_script. And it seems like everyone is ok with it.

So am I missing or misunderstanding something here?


EDIT

The codex has been modified. It now says:

This function will not work if it is called from a wp_head or wp_print_scripts actions, as the files need to be enqueued before those actions are run. See the Usage section for the correct hooks to use.

Related posts

Leave a Reply

1 comment

  1. Yeah, I been there lots of times. The short answer is all those guys that print script requests are all wrong or as some folks suggest it is faster not to use wp_enqueue_script but to load everything dynamically with Modernizr.load (yesnope.js) or any other js loader lib.

    My recommendation would be to stick with wp_enqueue_script as the best practice, but if you are developing themes for mobile, or you are extremely worried about speed and not bloating your browser with requests, I really recommend to load everything dynamically with a single js file (that you may call with wp_enqueue_script). Even consider inlining everything out and not loading jQuery but zepto.js or so.

    Many developers do this terrible practice of loading everything printed, not only bad taste, but terrible for experienced theme developers I might say :S

    For example thematic and several other blank themes rely on this practices and this truncates development speed with childthemes.

    If you are not sure about wp_enqueue_script just give the wordpress codex a read. It is thoroughly documented.

    Regards,