Skip to content

Instantly share code, notes, and snippets.

@katsar0v
Last active July 25, 2021 11:06
Show Gist options
  • Save katsar0v/dcc5e32f31a363343b4fd98122ff8d21 to your computer and use it in GitHub Desktop.
Save katsar0v/dcc5e32f31a363343b4fd98122ff8d21 to your computer and use it in GitHub Desktop.
Delay Inline JavaScript With W3 Total Cache
<?php
add_filter('w3tc_process_content', function( $content ) {
preg_match_all( "/<script(?:[^>]*)>(?<content>[\s\S]*?)<\/script>/ims", $content, $matches, PREG_SET_ORDER );
foreach ( $matches as $code ) {
if ( strpos( $code['content'], 'jQuery(' ) === false ) {
continue;
}
if ( strpos( $code['content'], 'DOMContentLoaded' ) !== false ) {
continue;
}
if ( empty( $code['content'] ) ) {
continue;
}
if ( preg_match( '/(application\/ld\+json)/i', $code[0] ) ) {
continue;
}
$new_code = "<script>document.addEventListener('DOMContentLoaded', () => { " . $code['content'] . "});</script>";
$content = str_replace( $code[0], $new_code, $content );
}
return $content;
}, PHP_INT_MAX);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment