WordPress WordPress Theme Development WordPress Header and Footer Templates Porting existing headers and footers into WordPress

Stefan Cutajar
Stefan Cutajar
7,745 Points

What if you have certain js files that are not used in all the pages is there any way to load them only when required?

I am following Zak to integrate my static theme to wordpress, however I have certain js files that are only being used in one page. How can I only load these files when required instead on every page like it is done on the video?

1 Answer

There's a couple of options here.

The easy one and the more technical, JS related one.

Easy WP option is to make use of template conditionals and wrap the enqueue instruction in this conditional. For example, if you only want your JS file to be loaded on the homepage, you'd wrap the enqueue for that file in an if(is_frontpage) conditional.

The more technical, and IMO preferred option, is to use JS to target an element and only run the JS when that element is present. This also helps with the scope of the JS as the trigger element becomes the subject of the function and you work from that. This also means you keep all your JS in one file and only the JS you want to use from that file runs when you tell it to. Might be a bit advanced but worth looking into for the future.

Always worth remembering that any caching plugin will want to combine the assets files (JS, CSS etc) into one file so if you're splitting them up depending on page, it can't do that and you don't get the greatest benefit from performance enhancements.