Meks
Do you know you can try any of our premium WordPress themes for free?Show me the themes
Load JavaScript only on specific WordPress pages

Load JavaScript only on specific WordPress pages

64Shares

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.

Top WP Hosting recommended by Meks

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:

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.

64Shares
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.

Try theme now for free!
  • Access to a copy of the demo website
  • Full access to the theme options
  • No credit card required

* We will send you an occasional newsletter with special offers, news & theme updates but you can unsubscribe at any time.

Meks