When to use add_action(‘init’) vs add_action(‘wp_enqueue_scripts’)

A lot of plugin developers don’t do things the right way. The right way is to hook on to wp_enqueue_scripts like you’re trying to do.

However, here’s the order of the hooks run in a typical request:

  • muplugins_loaded
  • registered_taxonomy
  • registered_post_type
  • plugins_loaded
  • sanitize_comment_cookies
  • setup_theme
  • load_textdomain
  • after_setup_theme
  • auth_cookie_malformed
  • auth_cookie_valid
  • set_current_user
  • init
  • widgets_init
  • register_sidebar
  • wp_register_sidebar_widget
  • wp_default_scripts
  • wp_default_stypes
  • admin_bar_init
  • add_admin_bar_menus
  • wp_loaded
  • parse_request
  • send_headers
  • parse_query
  • pre_get_posts
  • posts_selection
  • wp
  • template_redirect
  • get_header
  • wp_head
  • wp_enqueue_scripts
  • wp_print_styles
  • wp_print_scripts
  • … a lot more

The thing is, several developers were originally told to hook on to init for enqueue-ing their scripts. Back before we had a wp_enqueue_script hook, that was the “correct” way to do things, and tutorials perpetuating the practice are still floating around on the Internet corrupting otherwise good developers.

My recommendation would be to split your function into two parts. Do your wp_deregister_script/wp_register_script on the init hook and use the wp_enqueue_scripts hook when you actually enqueue jQuery.

This will keep you in the world of “doing it right” for enqueue-ing your scripts, and will help protect you from the hundreds of developers still “doing it wrong” by swapping jQuery for your concatenated version before they add it to the queue.

You’ll also want to add your init hook with a high priority:

add_action( 'init', 'swap_out_jquery', 1 );
function swap_out_jquery() {
    // ...
}

Leave a Comment