Excluding External JS From Minification

Sometimes there can be an issue with external JavaScript files and minification. External files cannot be minified, but they do get moved to the top of the page. To stop this from happening you can use the code below in either a MU plugin, or in the functions.php of your theme.

For example, if you would notice an issue with a file like this:

https://cdnjs.cloudflare.com/ajax/libs/Flowtype.js/1.1.0/flowtype.min.js

…the part of the URL that you would need to exclude from WP Rocket’s file optimization would look like this:

cdnjs.cloudflare.com

Similarly you would trim any other external file URL to its (sub-)domain part only.

Exclude via Custom MU Plugin

Follow the general instructions in this article:
How to Make a Custom (MU) Plugin

1
Create a folder named mu-plugins in your wp-content folder.
In case a mu-plugins folder already exists, don’t create a new one, just use the existing one.
2
Using a basic text editor create a new file and put the following code in it:
<?php
defined( 'ABSPATH' ) or die( 'Cheatin&#8217; uh?' );
/**
 * Plugin Name: WP Rocket | External Script Handler
 * Description: Exclude external scripts from WP Rocket’s file optimization.
 * Author:      WP Rocket Support Team (Jonathan)
 * License:     GNU General Public License v3 or later
 * License URI: http://www.gnu.org/licenses/gpl-3.0.html
 */

/**
 * Exclude external scripts from WP Rocket’s file optimization.
 * @param  array  $external_js Array of external domains
 * @return array               Extended array of external domains
 */
function __fix_wprocket_excluded_external_js( $external_js ) {

	/**
	 * Replace with your external script domain.
	 */
	$external_js[] = 'cdnjs.cloudflare.com';

	return $external_js;
}
add_filter( 'rocket_minify_excluded_external_js', '__fix_wprocket_excluded_external_js' );
	
3
Save the file as wp-rocket-external-js.php
4
Upload this file to the mu-plugins folder created in step 1.
5
Finally, make sure to deactivate and re-activate WP Rocket.

Exclude via your Theme

Place the below snippet in the functions.php of your child theme or custom theme.

/**
 * Exclude external scripts from WP Rocket’s file optimization.
 * @param  array  $external_js Array of script URL fragments
 * @return array               Extended array of script URL fragments
 */
function __fix_wprocket_excluded_external_js( $external_js ) {

	/**
	 * Replace with your external script URL part.
	 */
	$external_js[] = 'cdnjs.cloudflare.com';

	return $external_js;
}
add_filter( 'rocket_minify_excluded_external_js', '__fix_wprocket_excluded_external_js' );