Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Stefan Cutajar7,747 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?
Matt Campbell9,767 Points
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.