Skip to content

Instantly share code, notes, and snippets.

@juliquiron
Created August 2, 2019 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliquiron/36c58cf2d319804d1d86af9603171fb1 to your computer and use it in GitHub Desktop.
Save juliquiron/36c58cf2d319804d1d86af9603171fb1 to your computer and use it in GitHub Desktop.
Deferring WooCommerce inlined scripts
/**
* Minify to base64 URL and defer WooCommerce script.
*
* @param string $js The JS being rendered.
*/
function yournamespace_woocommerce_queued_js( string $js ) : string {
// Cleanup and get JS inside the wrapper <script> tag.
$remove_comments_regex = '/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\')\/\/.*))/';
$js = preg_replace( $remove_comments_regex, '', $js );
$js = str_replace( PHP_EOL, ' ', $js );
preg_match( '/<script[^>]*>(.*)<\/script>/', $js, $matches );
// Cleanup with soft minification and encode it.
$minified_js = preg_replace( [ '/\s+\n/', '/\n\s+/', '/[ \r\t]+/' ], [ '\n', '\n ', ' ' ], $matches[1] );
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions
$url_encoded_js = base64_encode( $minified_js );
// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
return '<script type="text/javascript" src="data:text/javascript;base64,' . $url_encoded_js . '" defer></script>';
}
add_filter( 'woocommerce_queued_js', 'yournamespace_woocommerce_queued_js' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment