Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save n7studios/5a54365fb31b159ca3cc1b8246eb3d74 to your computer and use it in GitHub Desktop.
Save n7studios/5a54365fb31b159ca3cc1b8246eb3d74 to your computer and use it in GitHub Desktop.
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment