Conditional JS and CSS Enqueueing on Front-End Pages

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:

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:

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

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:

Then add your callback function for the wp_head filter:

So the full code will look like:


Summary

References In This Article

WordPress functions

WordPress filters

WordPress template files

  • single.php
  • author.php
Tags:

Comments

Related Articles