Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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