One of the best ways to optimize your site is to only load scripts when you need them. If you only have a slideshow on your front page, then only need the script for it there, so don’t load it anyplace else. There are some plugins that can take care of that for you such as W3 Total Cache, but today I’m going to show you how to set this up inside your theme.
The beest way to load scripts in your WordPress theme is in your functions.php file or some file loaded by it. The first part is registering the scripts we will be using. That will look like this:
[php] if( !is_admin()){wp_register_script(‘flex’, get_template_directory_uri() . ‘/js/flexslider.js’, array(‘jquery’), ‘1.8.0’, true );
wp_register_script(‘vids’, get_template_directory_uri() . ‘/js/fitvids.js’, array(‘jquery’), ‘1.0.0’, true );
wp_register_script(‘custom’, get_template_directory_uri() . ‘/js/custom.js’, array(‘jquery’), ‘1.0.0’, true );
}
[/php]
The first part is a quick conditional that tells WordPress that we only want to register these scripts when we’re not in the admin. You may need to load some scripts for your theme in the admin section, but for our purposes today, we only want to load our scripts on the front end of our site. That’s what the !is_admin() does for us.
Then comes the wp_register_script that we use to let WordPress know about our script. Take the first registered script. We begin by giving the script a “handle” by which it will be know by in WordPress. Next is the location of the script; in this case inside a folder called JS inside our theme folder. After that comes the version of the script. If you care about security, you should include this. If you leave it blank, WordPress will use its version number instead. Last is a true/false setting that lets you specify if the script is loaded in the header (false) or in the footer (true).
Now that we have our scripts registered, it’s time to load them so we can use them. Here’s what the function looks like:
[php] function organizedthemes_load_default_scripts() {if( !is_admin()){
wp_enqueue_script(‘vids’);
wp_enqueue_script(‘custom’);
}
}
add_action(‘wp_enqueue_scripts’, ‘organizedthemes_load_default_scripts’);
[/php]
Here we create a function. For the function name, we want it to be unique and we also want it to describe what it does. So we’re calling it organizedthemes (the unique part) load_default_scripts (the descriptive part). Inside of that we’re enqueuing two scripts, one for our responsive video script since that could be used on any page, and also for the custom script that’s unique to our theme as it will be needed on all pages. We add our function to an action, in this case wp_enqueue_scripts so the scripts we’re calling will be loaded properly.
So now that we know how to load our scripts on all pages, how do we do this conditionally? We use one of WordPress’ great conditional tags.
[php] function organizedthemes_conditional_script_loading() {if ( is_home() || has_post_format( ‘gallery’ ) ) {
wp_enqueue_script(‘flex’);
}
}
add_action(‘wp_enqueue_scripts’, ‘organizedthemes_conditional_script_loading’);
[/php]
In this case, we will need the flex sider script to be available on the home page that’s the is_home() part of the function. We’ll also need it when a page/post has a gallery post format. That’s the has_post_format( ‘gallery’ ) part. The || means “or” so if the visitor is on the home page or is viewing a page/post with the post format of gallery then the next part of our function will happen. But only then.
Just remember, the conditional tags have to be used inside a function in order for this to work.
So that’s how to register your scripts and then apply them to the front of your site only when necessary. If you have any creative uses for this, let us know in the comments.
Jim Frenette August 18, 2015
Hi Bill,
Nice post – I would like to share another way to use wp_enqueue_style and wp_enqueue_script using the custom fields available to post and page editors: http://jimfrenette.com/2015/07/wordpress-page-specific-styles-or-scripts/ – dependecies are also handled in my functions.php solution. Please let me know what you think.
Cheers,
Jim
Bill Robbins August 19, 2015
Hello Jim,
You can do that. There are lots of options for enqueuing scripts and styles only when you need to. Custom fields in certainly possible and fits in nicely when you only need those files occasionally.
Take care,
Bill
Eric April 30, 2015
Just wanted to chime in and thank you for this. I hadn’t been using the action hook to load my scripts and while that worked for default scripts 95% of the time, conditional loading wouldn’t work that way. Thanks much!
Bill Robbins April 30, 2015
Glad that helped out Eric!
Chandu June 28, 2014
Exactly what I was looking for. Thanks a lot.
I have a bumch of templates where I want to include some scripts. Is there a variant if is_teplate_page that accepts an array of template pages?
Bill Robbins June 28, 2014
Unfortunately is_page_template doesn’t accept more than one value, but you could create something like this if ( is_page_template( ‘template.php’ ) || is_page_template( ‘template_2.php’ ) ) where the || serves as an “or” statement.
Tahir Yasin June 17, 2014
Script Logic is a WordPress plugin that gives you full control over all JavaScript and CSS files. Using this plugin you can conditionally load CSS and JS file only on pages where needed.
http://wordpress.org/plugins/script-logic/
Hadi Zahedi June 13, 2014
Hi. How can I add a script to a woocommerce Checkout Header only? it about conversion advertising on facebook just on checkout page.
thanks
Bill Robbins June 17, 2014
You can do that. Your conditional statement could look something like this:
Where share is the handle for your script that’s registered. In this case Checkout is the name of the page where the script is being enqueued.
Rushi April 16, 2014
Hello,
How to call js and css for particular post ?
I want to call different js and css for only one post which has custom post type.
Please help me.
Thank you
Bill Robbins April 16, 2014
WordPress’ conditional tags will let you target a specific post. Instead of this line:
you would use something like this:
where Post Title is the title of your post. Then you can enqueue your scripts only on that specific post.
Loading a stylesheet works basically like a script. You just use wp_register_style instead of wp_register_script and wp_enqueue_style instead of wp_enqueue_script. You’ll still want to load the styles with the wp_enqueue_scripts action. You can read about those functions at http://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts and http://codex.wordpress.org/Function_Reference/wp_register_style
Hope that helps out
Raffael Schulz November 15, 2013
Thanks! Took me a while to find it and this is exactly what I need.
Does that method work with WordPress plugins like W3 Total Cache when I use it to combine all JS files into one file?
Bill Robbins November 15, 2013
Good question. I believe W3 Total Cache has the ability to combine your JS files conditionally built-in. It’s been a while since I last used the plugin, but I believe I remember it having that functionality. If it does, you’ll want to use that to combine your JS files instead of conditional statements in the theme.
Mike October 15, 2013
I have a couple of questions:
1) Does register & enqueue_script override plugins that want to load javascript, or does something have to be done to prevent a plugin from loading a script?
2) Can you load scripts based on the end user’s device? I’d love to not load a slideshow script on phones and tablets, that I’m want to use on desktops and laptops.
Bill Robbins October 16, 2013
Mike,
Good questions. There is another WordPress function called WP Dequeue Script (http://codex.wordpress.org/Function_Reference/wp_dequeue_script) that you can use to stop a plugin from loading a script. WordPress loads in this order: core, plugins, child theme, parent theme, so you can add the wp_dequeue_script function to your theme and it can affect what’s already happened in a plugin.
It is also possible to detect a mobile device and change what’s served to them based on that. There are several code libraries out there that will make that happen for you. One is “Mobile-Detect” https://github.com/serbanghita/Mobile-Detect#projects-that-are-using-the-class which you could roll into your theme.
The main drawbacks are it requires the mobile browser to represent itself accurately. That sometimes doesn’t happen and can be faked too. Also it may cause trouble with caching too.
Another option, and probably the more reliable one, is to use Modernizr (http://modernizr.com) to detect features in the mobile browser and then serve what’s needed there.
Hope that helps out,
Bill
Muhammad Hussain September 25, 2013
Can you let me know how to add script on in some template like I have custom template called exp how I load script only on it ?
Bill Robbins September 25, 2013
You can do that. What you’ll want to do is register your script like I mentioned above. Then to load the script, you’ll want to use something like this:
Just replace the exp.php with the file name of your page template. You’ll also want to change the flex to match the name you gave the script when you registered it.
That will cause the script to only be loaded on that page template.
Peter Drinnan July 9, 2013
This is a method I have been recommending for a couple of years now. I know a lot of “engineer” programmers who do not appreciate the importance of not loading everything but the kitchen sink on every page load.
Bill Robbins July 9, 2013
So true. I cringe when I look at a theme or plugin that loads 18 jQuery plugins and stylesheets on every page. Combine them and only use them when necessary.
Brad Dalton July 7, 2013
Just wrote about this myself today and was looking around after i published the post to see what others have done.
Reading on Weblog tools that they say you don’t need to register the script if using the path to the file, then you only need to enqueue it. http://weblogtoolscollection.com/archives/2010/05/06/adding-scripts-properly-to-wordpress-part-1-wp_enqueue_script/
Bill Robbins July 7, 2013
Brad, thanks for sharing. Great point. I generally register and enqueue them separately because I tend to use the same scripts across my themes, but employ them in different ways. On one theme, I may only use a slideshow script on the home page; on another it’ll be used on the home page and with the gallery post format. It worked out well for me to have those two items separate so I could move them around a bit more easily. For a lot of situations it makes great sense to do it all in one step.
Nick Meagher May 29, 2013
Great article, I have been using this method to call my scripts/styles but was having a js conflict with gravity forms and using the conditional statement fixed it.
Thank you!
Bill Robbins May 29, 2013
I’m glad that helped out Nick.
lemonthirst April 3, 2013
Hello, just what i have been looking for, i am trying to add scripts to load conditionally, on one of my websites to speed it a little bit.
off topic
i don’t know why people(developers) don’t use this feature more often
Thank for the great article
Bill Robbins April 3, 2013
Glad to hear that helped you out. I do wish more developers would do this with their themes (and plugins). You can really speed things up by cutting down on unnecessary requests.