Loading JavaScript Conditionally


Web Development

Updated Jul 11th, 2023

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.

Example for WordPress Page-Specific JavaScript

/* enqueue script to conditionally load page-specific js for style-guide page id# */
function load_style_guide_js() {
    if( is_page( 1827 ) ) {
        wp_enqueue_script('custom-style-guide-js', get_theme_file_uri('/js/style-guide.js'), NULL, '1.0', true);
    } 
}
add_action('wp_enqueue_scripts', 'load_style_guide_js');