1

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.

2

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' );
    }
}
  • 1
    Thanks. However, I think that he wp_register_script() and wp_register_style() you are referencing are functions, not hooks. – Greeso Aug 25 '17 at 19:03
  • Thanks. So is wp_loaded called only once? The reason for my question is, should I register scripts and styles whenever wp_loaded is called? or during plugin registration, using 'register_activation_hook()'? – Greeso Aug 25 '17 at 19:11
  • My bad! Updated answer. Yes, it's only called once. "This hook is fired once WP, all plugins, and the theme are fully loaded and instantiated." see wp-settings.php – Dave Romsey Aug 25 '17 at 19:14
  • But every time I refresh the page, wp_loaded is triggered again, right? – Greeso Aug 25 '17 at 19:15
  • Yes, of course but it's only fired once per request. – Dave Romsey Aug 25 '17 at 19:18

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.