When it comes to JavaScript and WordPress, we bet you have seen various approaches for loading JavaScript in your theme front-end. As a good practice and the most elegant way, WordPress uses its wp_enqueue_script() function.
When you load some custom front-end JavaScripts in your theme, the proper code usually looks something like this:
1 2 3 4 5 6 7 8 9 10 | //Register hook to load scripts add_action('wp_enqueue_scripts', 'my_theme_load_scripts'); //Load scripts (and/or styles) function my_theme_load_scripts(){ wp_enqueue_script('jquery'); wp_enqueue_script('my_first_script', get_template_directory_uri() . '/js/my_first_script.js'); wp_enqueue_script('my_second_script', get_template_directory_uri() . '/js/my_second_script.js'); wp_enqueue_script('my_third_script', get_template_directory_uri() . '/js/my_third_script.js'); } |
Ok, so far so good. But in some cases we don’t need to load all scripts on every page but only for specific page template(s). In the previous example your theme will load every script on every front-end page which may slow down page load every time someone visits your site.
Imagine that your theme have a page template called “Slider Portfolio” which for example handles your portfolio items with some jQuery slider (very common example), and you need that script only for that specific template. In the next small example we are going to show you how can you load some script only for the page template which needs it, instead of every page.
So, how to add JavaScript to a specific page only?
Here’s addition to the previous code example and the solution we came up to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //Register hook to load scripts add_action('wp_enqueue_scripts', 'my_theme_load_scripts'); //Load scripts (and/or styles) function my_theme_load_scripts(){ wp_enqueue_script('jquery'); wp_enqueue_script('my_first_script', get_template_directory_uri() . '/includes/js/my_first_script.js'); wp_enqueue_script('my_second_script', get_template_directory_uri() . '/includes/js/my_second_script.js'); if(is_page()){ //Check if we are viewing a page global $wp_query; //Check which template is assigned to current page we are looking at $template_name = get_post_meta( $wp_query->post->ID, '_wp_page_template', true ); if($template_name == 'slider-portfolio.php'){ //If page is using slider portfolio template then load our slider script wp_enqueue_script('my_third_script', get_template_directory_uri() .'/includes/js/my_third_script.js'); } } } |
In practice, it won’t be a big deal if you need to do this only for one script, but it’s very useful when your site uses large number of JavaScripts which don’t need to be loaded every time on every page. It’s pretty simple and still can speed up your page loading significantly. This way you will also reduce a chance to cause JavaScript errors which may brake other functionality on the site.