Managing JavaScript in WordPress themes

(Clifton Griffin) #1

You know how it goes. You start out with a few well selected libraries and implement them strategically to only load on certain pages, and then 2 years pass and you have a rats next that is not only unmanageable, but non-performant.

I’ve been looking at how to fix a client theme that has reached this state. At first, it seemed like using Gulp to concatenate and minify to a single global file was good enough. 25KB is no big deal these days.

But, stepping back, we realized we also have 20 support libraries (it’s a huge e-commerce site…) that are dependencies of this global file.

We’re going to trim any of these dependencies we can, but this pulls us back to kind of where we started: how do we selectively load only the JS that we need, where we need it, in a way that is sanely manageable?

Right now we’re doing this kind of things, ad infinitum:

if ( is_singular( 'foo' ) ) {
    wp_enqueue_style( 'bar-css' );
    wp_enqueue_script( 'bar-js' );

Is there a best practice here? Do you concatenate your JS libraries, as well as your custom JS? How do you approach splitting it into relevant chunks to avoid loading on all pages?

Is this just the nature of the beast?

Thanks in advance!

(Jason) #2

I do a similar setup:

switch (true) {
  case is_singular('foo'):
  case is_singular('bar'):

  case is_post_type_archive('foo'):


Outside of some sort of convention (not a bad idea), I’m not really sure of how one would load the necessary scripts without doing so manually.

Very curious to see how others handle it!

(Basilis Kanonidis) #3
function is_welcome()
     if (isset($_GET['page']) && $_GET['page'] == 'welcome') {
          return true;
     return false;

and then use the following

function theme_welcome_scripts_styles() {
    wp_enqueue_script( 'admin-scripts', THEME_ADMIN_ASSETS_URI .'/js/admin-scripts.js');
    wp_enqueue_style( 'admin-styles', THEME_ADMIN_ASSETS_URI .'/css/admin.css');

if(is_welcome()) {
    add_action( 'admin_print_scripts', 'theme_welcome_scripts_styles' );

(Ionuț Staicu) #4

You could dequeue all libs and make use of something like RequireJS to load only what you need. However, this may be hard to do on an existing site (since all JS needs to be written in a certain way).