Load JavaScript only on specific WordPress pages

Load JavaScript only on specific WordPress pages

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:

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.

Here’s addition to the previous code example and the solution we came up to:

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.

Bojan Petrovic

Co-founder and WordPress developer at Meks. He has been involved in the business since 2009. creating themes, plugins and services on top of WordPress, continuously aiming to choose best approaches and work smarter, not harder.

5 comments

Leave a comment
  • Excellent article.

    But the problem is, deciphering scripts needed by pages, is difficult. Theme publishers do not discuss these intricate topics. If someone creates an “analyzing” plugin for the job, I can see everyone grabbing that plugin. Even Google will be happy!

    Thanks.

  • Just a quick point:

    in your second script, line 15:
    $template_name = get_post_meta( $wp_query->post->ID, ‘_wp_page_template’, true );

    The text that you’ve copied and pasted includes “->” instead of ->
    So it crashes the page.
    Should read something like:
    wp_enqueue_script(‘jquery_min_script’, get_stylesheet_directory_uri() .’/archetypes_files/js/jquery.min.js’);
    Note that I’ve used ‘get_stylesheet_directory_uri()’ because I’m using a Child Theme.

  • ah so that didn’t render properly – the ‘ampersand gt smicolon’ appears in your code, not the ‘dash hyphen’ on line 15.
    Does that make sense?

Leave a Reply

Your email address will not be published. Required fields are marked *