Shoora
4/22/2019 - 9:37 AM

Autoptimize Inline Javascript Minification Fault

Autoptimize Inline Javascript Minification Fault

<?php
/**
 * Plugin Name: Autoptimize Inline JS Fault
 * Plugin URI:  http://www.n7studios.co.uk
 * Description: Demonstrates a fault with Autoptimize where "Also aggregate inline JS" is enabled but not honoured.
 * Author:      Tim Carr
 * Author URI:  http://www.n7studios.co.uk
 * Version:     1.0.0
 */

/**
 * Adds inline Javascript to the footer of the WordPress web site, which will fail to be removed
 * and added to Autoptimize's minified JS file.
 *
 * To reproduce the fault:
 * - WordPress 4.5.2
 * - Autoptimize 2.0.2
 * - Activate this Plugin
 *
 * Make sure Autoptimize has the following settings:
 * - Optimize Javascript Code: Yes
 * - Force Javascript in head: No
 * - Also aggregate inline JS: Yes
 *
 * Load any Page, and you will see that the inline Javascript does not get aggregated into Autoptimize's 
 * minified JS file.
 *
 * This is because the Javascript includes src=", which Autoptimize greedily evaluates through preg_match
 * at classes/autoptimizeScripts.php:99:
 * preg_match('#src=("|\')(.*)("|\')#Usmi',$tag,$source)
 *
 * Autoptimize then attempts to determine whether the src item is an external or inline JS file, when it
 * should just ignore the src declaration altogether (as it's for an image).
 */
add_action( 'wp_footer', 'autoptimize_fault_wp_footer' );
function autoptimize_fault_wp_footer() {

	?>
	<script type="text/javascript">
		console.log( '<img src="http://placehold.it/400x400" />' );
	</script>
	<?php

}