When should you use add_action
to enqueue or register a script, vs just using wp_register_script
and/or wp_enqueue_script
? In other words, both example 1
and example 2
below seem to accomplish the same thing when in functions.php
, so why do so many resources say that example 1
is the correct way of loading scripts in WP?
Example 1:
function my_assets() {
wp_register_script( 'owl-carousel', get_stylesheet_directory_uri() . '/owl.carousel.js', array( 'jquery' ) );
wp_enqueue_script( 'owl-carousel' );
}
add_action( 'wp_enqueue_scripts', 'my_assets' );
Example 2:
wp_register_script( 'owl-carousel', get_stylesheet_directory_uri() . '/owl.carousel.js', array( 'jquery' ) );
wp_enqueue_script( 'owl-carousel' );
(yes, I know in example 2 you could skip registering the script and just enqueue it as necessary)