Execute javascript when NOT in a certain route

What is the best way to execute some javascript when NOT on a specific page? I have this case where some JS should be executed on all pages except for the homepage.

Perhaps I could check in the common.js file whether I’m in the homepage?
if( window.location.href === 'http://example.com') doesn’t really seem like a good practice…

Put your function in the finalize method on common, but have it check for a “don’t run” variable before running. Then set that variable in the init method on any route where you don’t want it run.

3 Likes

If you wanted to centralize things, you could also check the body classes rather than a variable set in the init methods:

const blacklist = ['home', 'single-post'];
const bodyClasses = Array.from(document.body.classList);

if (!bodyClasses.some(bodyClass => blacklist.includes(bodyClass))) {
  console.log('not on home or single post');
}
3 Likes

This topic was automatically closed after 42 days. New replies are no longer allowed.