Loading JavaScript Conditionally


Web Development

Updated Feb 15th, 2021

Note: If your JavaScript is looking for something that’s not on the page It will throw a console error. To avoid this add “if element exists then do this” so if it doesn’t exist nothing will happen.

Another reason to load JavaScript conditionally is to reduce bloat in your JavaScript file and download code only when the user needs it.

This code splitting essentially calls the import function only when needed and is the preferred way to load JavaScript conditionally.

Another way, which was the first way I learned, involved running a PHP function (WordPress) to only load JavaScript files for specific pages IDs. This strategy still works although this is reliant on a page ID so makes local to live development difficult because oftentimes your page or post ID is different. This strategy does still have the benefit of creating a separate JavaScript file that is not In your main JavaScript file but I believe the code-splitting option above is still the better way.


Top