0

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)

1

Well it works the same in the case where you tested it.

The answer could actually be somewhat complex, but mainly having it inside an action callback only registers them when needed, just putting it inside the functions.php it happens always when the theme is active.

First of all this can be a waste of performance, registering stuff that is never used. You might think that it should be there in any case, but actually in WP there are plenty of situations where frontend JS/CSS is totally irrelevant. The most obvious situation is the backend. But also some plugin might create an endpoint that doesn't need JS/CSS. And there are plenty more of that.

Last but not least by having this on an action third party code (plugins, child themes) can unhook the callback to e.g. replace it with something else.

I hope this gives you a basic understanding why it is good practice to only do stuff on the appropriate hook.

To close things this could also be relevant/interesting for you: https://wordpress.stackexchange.com/a/21579/47733

0

The short answer to your question is time. wp_enqueue_scripts makes sure that scripts are available when needed.

wp_enqueue_scripts is the proper hook to use when enqueuing items that are meant to appear on the front end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.