Conditionally load plugin scripts and styles

You may find that you need to install a plugin to perform a certain function, but you only need it to work on a specific page or section of the website. If the plugin comes with scripts and styles, you’ll find that they are most likely being enqueued on all page, potentially affecting the load times of your website.

You can selectively deregister scripts and styles by entering the following into your functions.php file:

function plugin_deregister_styles() {
if ( is_home() || is_front_page() ) { } else {
add_action('wp_print_styles', 'plugin_deregister_styles', 100);

Note that the wp_deregister_ functions are preceded by an if statement, checking whether we were on the home page. In this case, I only wanted the scripts to load on the home page, and for all other pages I wanted them deregistered.

If you need to determine the naming of the scripts and styles to properly deregister them, you may need to search through the plugin to find where it enqueues everything. Once you do, you can find the ids of each, and apply them to your deregistration function.

wp_enqueue_script( 'photoswipe', $photoswipe_wp_plugin_path . '/photoswipe-dist/photoswipe.min.js');
wp_enqueue_script( 'photoswipe-masonry-js', $photoswipe_wp_plugin_path . '/photoswipe-masonry.js');