Last active
July 25, 2021 11:06
-
-
Save katsar0v/dcc5e32f31a363343b4fd98122ff8d21 to your computer and use it in GitHub Desktop.
Delay Inline JavaScript With W3 Total Cache
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
<?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