Conditionally Enqueue Script Files

When I redid my site last year, I found myself only wanting to enqueue the code for my p5.js effects on certain page(s) where the interactive nature of the purple orbs would be applied. To do so, I nested a conditional inside my theme’s regular wp_enqueue_scripts function in order to only load this particular JS file on the front page.

Conditional:

// Content for front page.
if ( is_front_page() ) {
     wp_enqueue_script( 'themePrefix-fileName', get_template_directory_uri() . '/assets/js/fileName.js', array(), '', true );
}

Full Snippet Example:

function atarr_scripts() {
	$version = '1.0.0';
	$suffix = ( true === $debug ) ? '' : '.min';

	// Enqueue regular scripts.
	wp_enqueue_script( 'atarr-scripts', get_template_directory_uri() . '/assets/js/project' . $suffix . '.js', array( 'jquery' ), $version, true );

	// Content for front page.
	if ( is_front_page() ) {
		wp_enqueue_script( 'atarr-heroine', get_template_directory_uri() . '/assets/js/heroine.js', array(), $version, true );
	}
}
add_action( 'wp_enqueue_scripts', 'atarr_scripts' );
Additional Reading:

Leave a Reply

Your email address will not be published.