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' );
}
}