Advertisement
Tips

Quick Tip: Conditional JavaScript and CSS Enqueueing on Front-End Pages

by

We've read it numerous times – a good WordPress citizen only loads their JavaScript where it is needed. This practice minimizes site load times and conflicts with other scripts. However, most articles only discuss the use of wp_enqueue_script for conditional JavaScript loading in the context of the WordPress admin, plugin admin pages, or front-end pages as a whole. But what about isolating our JavaScript to a particular front-end page? We could potentially get fancy with if statements, but WordPress provides a helpful API with a filter for handling just this sort of thing without if – so let's take a look under the hood.

"a good WordPress citizen only loads their JavaScript where it is needed"


Under The Hood


Template Loader

When a WordPress page is requested by a reader, the WordPress template loader checks to see if the proper template exists and a function named get_query_template is called. This function locates the proper template based on the WordPress page request and returns the full path to the template. However, before it returns the path, it allows the output to be changed using the {$type}_template filter. {$type} is the template's filename without the extension.


get_query_template Function

So if a reader was requesting a single post page on a site that used the Twenty Eleven theme, {$type} would evaluate to 'single' and we could use a filter named 'single_template' to change the path to the single post template before it was returned to be loaded by WordPress. This filter would look something like this:

add_filter( 'single_template', 'benchpress_single_template' );

function benchpress_single_template( $template_path ) {
	//do something here
	return $template_path;
}

and gives us exactly what we need: a way to target each specific page type/template file in order to isolate our JavaScript to particular WordPress front-end pages. Any page/template file can now be targeted by simply using a filter with the template file name. Awesome!

Now let's put it together step-by-step.


Putting It Together

Step 1 Add the proper filter to functions.php

Remember, the filter name will be the template file name without the extension. So using the Twenty Eleven theme and desiring to target our JavaScript to the author pages only, we would add the following code to our functions.php file:

add_filter( 'author_template', 'benchpress_author_template' );

Step 2 Enqueue our JavaScript (and CSS) files in the filter's callback function

function benchpress_author_template( $template_path ) {
	wp_enqueue_script( '{unique name for script}', get_stylesheet_directory_uri() . '{path/to/script}' );
	wp_enqueue_style( '{unique name for stylesheet}', get_stylesheet_directory_uri() . '{path/to/stylesheet}' );

	return $template_path;
}

Notice the filter passes the template path value to our callback and we return $template_path unharmed because we do not need to change it.

What about conditionally loading JavaScript that gets generated in my PHP?

I've seen this question asked and while I'm not sure that this is the best way, here is a way to handle this.

Add the following line to the filter's callback function:

add_action( 'wp_head', 'benchpress_dynamic_js' );

Then add your callback function for the wp_head filter:

function benchpress_dynamic_js() {
	if ( ! is_admin() )
		echo '<script></script>';
}

So the full code will look like:

add_filter( 'author_template', 'benchpress_author_template' );

function benchpress_author_template( $template_path ) {
	wp_enqueue_script( '{unique name for script}', get_stylesheet_directory_uri() . '{path/to/script}' );
	wp_enqueue_style( '{unique name for stylesheet}', get_stylesheet_directory_uri() . '{path/to/stylesheet}' );

	add_action( 'wp_head', 'benchpress_dynamic_js' );

	return $template_path;
}

function benchpress_dynamic_js() {
	if ( ! is_admin() )
		echo '<script></script>';
}

Summary

References In This Article

WordPress functions

WordPress filters

WordPress template files

  • single.php
  • author.php
Related Posts
  • Web Design
    UX
    Walk Users Through Your Website With Bootstrap TourTour retina
    When you have a web application which requires some getting used to from your users, a walkthrough of the interface is in order. Creating a walkthrough directly on top of the interface makes things very clear, so that's what we're going to build, using Bootstrap Tour.Read More…
  • Code
    Creative Coding
    Using WordPress for Web Application Development: Understanding Events, Actions, and FiltersApplication foundation 400
    Throughout this series, we've been taking a look at how WordPress can be used for building web applications. Up to this point, we've established that WordPress is a foundation - rather than a framework - and we've talked a bit about how we need to avoid trying to shoehorn WordPress into another type of design pattern than that of its native type.Read More…
  • Code
    Plugins
    Using HighCharts in WP-AdminHighcharts 400
    Charts are a great way to present data. They make data more digestible by making it visually appealing. In WordPress, there is no built-in method for getting posts and pages data in a graphical form. Although, there are certain plugins available which integrate Google Analytics with WordPress, but they are overkill if you want to get only a portion of that data. Also, nothing should keep you from learning new techniques and to dive straight into the subject is the best way to learn.Read More…
  • Code
    Theme Development
    Ensuring Your Theme Has Retina SupportRetina 400
    With all of the high resolution screens available today, it only makes sense that your WordPress theme includes support for displaying higher quality images. That means adding functionality to create these images on top of a way to load the right one depending on the screen resolution of the end user.Read More…
  • Code
    Cheat Sheets
    The Complete Guide to Proper JavaScript Usage With WordPressJavascript 400
    I remember thinking "What the heck do we need JavaScript for, when we have Flash?" when I was fourteen. Although I still remember how I enjoyed coding stuff with ActionScript 2.0 back then, I saw how much one can achieve with JavaScript and fell in love with it. I'm not an expert on JavaScript (yet) but I can say I'm over and done with Flash for a long time. When it comes to WordPress, the biggest blogging platform and content management system worldwide, JavaScript is - of course - very useful for many things: content sliders, lightbox galleries, slick shopping carts, UI elements like tabs or accordions... you name it. But how exactly should we use JavaScript with WordPress? Returning or echoing a bunch of HTML script elements is one way to do it - and it's wrong. In this tutorial, we're going to see how to enqueue JavaScript files inside our pages and how to pass translatable data to the JavaScript code.Read More…
  • Code
    Tips
    Common WordPress Development Mistakes and How to Fix ThemCommon wordpress development mistakes and how to fix them
    With WordPress becoming more and more popular there is a massive amount of code being generated by users, agencies and marketplaces. I've been working with WordPress for a long time and it amazes me how many developers out there are making the same mistakes over and over again. I'm going to go through some of the most common development mistakes and how you can easily fix them, and going forward make your code better!Read More…