When using wp_enqueue_script(); in a theme why don’t we use add_action?

When using wp_enqueue_script in a plugin, I have always been told to use an add_action :

function add_my_css_and_my_js_files(){
    wp_enqueue_script('jquery-validate-min', plugins_url('jquery_validate_min.js', __FILE__ ) 
    }
add_action('wp_enqueue_scripts', "add_my_css_and_my_js_files");  

How come this is not required if you put wp_enqueue_script in the theme:

 wp_enqueue_script('jquery-validate-min', plugins_url('jquery_validate_min.js', 

Related posts

Leave a Reply

2 comments

  1. It is required, actually.

    There’s no real difference between themes and plugins as such. Neither of them should take actions on merely being loaded, they should use action hooks on functions to have things happen in the correct ordering.

  2. When you pour some water into a glass, first you put the glass on the table, then you turn the bottle.

    If you first turn the bottle, and then put glass on the table, your floor gets wet and your glass stay empty.

    Actually wp_enqueue_scripts is just a way to save a variable (water) inside a global object (glass), so before to call the function (turn the bottle) you must be sure that the global object is declared (the glass is on the table).

    When you write add_action('wp_enqueue_scripts', 'add_my_css_and_my_js_files'); you are saying to WordPress: “When the glass is on the table, turn the bottle and fill the glass.” and that prevent your site to get wet.

    Actually, if you are absolutely sure that the global object is declared you can call wp_enqueue_scripts without adding an action. E.g. a case is when you add some scripts from a shortcode callback: there you can call wp_enqueue_scripts direclty, and the script will be added in the footer (because the header was already printed at that time, and WordPress does not include a time machine).

    So there is no difference from plugins and themes, because both can do things before or after the right time: add the action to be sure that timing is respected.