Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialStefan Cutajar
7,747 PointsWhat 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
Matt Campbell
9,767 PointsThere'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.