Created
August 2, 2019 11:57
-
-
Save juliquiron/36c58cf2d319804d1d86af9603171fb1 to your computer and use it in GitHub Desktop.
Deferring WooCommerce inlined scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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