Connecting Scripts/Styles if Shortcode is Present in the Content

Connection and Verification on All Pages

This code shows how to connect a script or style file conditionally - if a specified shortcode is present in the displayed content.

// Connect the script if the specified shortcode is present on the page.
// Use a filter as an event.
add_filter( 'the_posts', 'has_my_shortcode' );

function has_my_shortcode( $posts ){

	if( is_admin() || empty( $posts ) || ! is_main_query() ){
		return $posts;
	}

	$shortcode_name = 'my_shortcode';

	foreach( $posts as $post ){

		if( has_shortcode( $post->post_content, $shortcode_name ) ){
			add_action( 'wp_enqueue_scripts', 'add_my_scripts' );

			break;
		}
	}

	return $posts;
}

// Enqueue scripts if shortcode is present
function add_my_scripts() {
	$theme_url = get_stylesheet_directory_uri();

	wp_enqueue_script( 'my_script', "{$theme_url}/my_script.js" );
}

Connection and Verification for Individual Pages - is_singular()

// Connecting scripts/styles if shortcode is present in the content
add_action( 'wp_head', 'my_shortcode_styles' );

function my_shortcode_styles() {
	global $post;

	$shortcode_name = 'my_shortcode_name';

	if(
		! ( $post && is_singular() && has_shortcode( $post->post_content, $shortcode_name ) )
	){
		return;
	}

	?>
	<style>
		.foo{ color: red; }
	</style>
	<?php
}