Best spot for wp_register_script() and wp_register_style()

I need to enqueue multiple scripts and styles in my plugin. However, I do not like the idea of calling wp_register_script() and wp_register_style() every time I need to call wp_enqueue_script() and wp_enqueue_style(). I think it is a good idea to register the scripts and styles once, then call them as necessary as needed.

So my question is, what is the best practice to using an action hook to call wp_register_script() and wp_register_style() to enable one-time registration? And which action hook is it?

Thanks.

1 Answer
1

Scripts and styles can be registered on the wp_loaded hook and then later enqueued using wp_enqueue_scripts.

Once the scripts and styles have been registered, they can be enqueued later using just the handles that they were originally registered with.

// Register scripts/styles. They can be optionally enqueued later on.
add_action( 'wp_loaded', 'wpse_register_scripts' );
function wpse_register_scripts() {
    wp_register_script( 'something-js', get_template_directory_uri() . '/js/something.js', array( 'jquery' ), true );
    wp_register_script( 'something-else-js', get_template_directory_uri() . '/js/something-else.js', array(), true );
    wp_register_script( 'another-something-else-js', get_template_directory_uri() . '/js/another-something-else.js', array(), true );
}

// Enqueue scripts/styles.
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_scripts' );
function wpse_enqueue_scripts() {
    // Load everywhere.
    wp_enqueue_script( 'something-js' );

    // Only enqueue scripts/styles on static front page.
    if ( is_front_page() ) {
        wp_enqueue_script( 'something-else-js' );
    }

    // Only enqueue scripts/styles when the full-width.php template is used.
    if ( is_page_template( 'full-width.php' ) ) {
        wp_enqueue_script( 'another-something-else-js' );
    }
}

Leave a Comment