JavaScript only on certain pages

_main.js has different sections for different pages, like this:

  // Home page
  home: {
    init: function() {
      // JS here
    }
  },

I want to add one for a certain category by using the category class that gets added to the body of category pages, like this:

// Resources page
  category-resources: {
    init: function() {
      // JS here
    }
  },

But the hyphen in category-resources stops it compiling:

Linting assets/js/_main.js...ERROR
[L19:C11] Expected ':' and instead saw '-'.
  category-resources: {

Is there any way round this? I can’t use the id instead of the slug because it also has a hyphen (category-5).

Or should I just forget this and put all my code in the “common” section? Is the advantage of making it page-specific just a speed thing or are there also security reasons?

I have yet to explore this technique, so I could be way off. Looking at the loadEvents functions leads me to believe if you are trying to target a class called category-resources you would replace the hyphen with an underscore when adding it to the ExampleSite obj. Try this and let me know if it works:

// Resources page
  category_resources: {
    init: function() {
      // JS here
    }
  },

In my experience hyphenating keys in JS objects can lead to some headaches so I can understand why they would build it this way.

2 Likes

Yes, that worked!

Now you’ve said it I can see which line does the replacing, but I never would have figured that out by myself.

Many thanks. :slight_smile:

Not a problem, I am glad to have helped :smile:

It looks this line is one of the Roots specific modifications of the method to account for WordPress’ use of hyphenated classes

Generally if you are hyphenating a obj key you must wrap it in quotes and you cannot access it by obj.my-Prop so you must use obj["my-Prop"]. There are many instances where you would prefer to use the first method, so you must avoid using hyphens then.
I often forget this little fact myself so hopefully this post will serve as a reminder and save me some time debugging.

I am curious to hear what your thoughts are on this method. It almost feels like a magic way to avoid having multiple JS files and a mess of PHP conditionals. Let me know if you learn anything interesting along the way.

Exactly right. We’ll need to add some documentation for this since it isn’t yet mentioned anywhere

1 Like

If nobody else gets to it before me, then I volunteer to write docs for this. It would be a great way to learn the ins and outs of the technique and contribute back to the Roots community. However, I won’t be able to get to it for the next few days to a week.