Quantcast
Viewing all articles
Browse latest Browse all 13547

digitalsky on "How can I load certain JavaScripts only on blog pages?"

I figured it out. This is the code that did the trick (this goes in the function.php file)...

// Add our own JavaScripts.
function custom_scripts()
{
	// Register the scripts
	wp_register_script( 'modernizr', get_template_directory_uri() . '/js/modernizr-2.6.2.min.js', array(), '2.6.2', false );
	wp_register_script( 'formalize', get_template_directory_uri() . '/js/jquery.formalize.min.js', array(), '1.0', false );
	wp_register_script( 'social', get_template_directory_uri() . '/js/social.js', array(), '1.0', true );

	// Enqueue the scripts:
	wp_enqueue_script( 'modernizr' );
	wp_enqueue_script( 'formalize' );

	// Only enqueue the social script if we're on a 'single' post page (we don't want this script being loaded on pages without the social sharing icons):
	if ( is_single() ) {
		wp_enqueue_script( 'social' );
		echo '<script src="//platform.linkedin.com/in.js" type="text/javascript">lang: en_US</script>';
	}
}
add_action( 'wp_enqueue_scripts', 'custom_scripts' );

That code enqueues all of my scripts I've added on. It also detects whether the visitor is on a single post page and if so it loads the social.js script (which controls all my social media sharing buttons) in the footer of the site. Works like an absolute charm and ensures that these scripts are not being loaded on pages that don't need it. This is a nice fix for anyone who is concerned about page speed.


Viewing all articles
Browse latest Browse all 13547

Trending Articles