Fixed Render-blocking JQuery in wordpress with Autoptimize

author-avatarRAJESH, July 20, 2020

Autoptimize by default excludes inline JS and jquery.js from optimization. Inline JS is excluded because it is a typical cache-buster (due to changing variables in it) and as inline JS often requires jQuery being available as a consequence that needs to be excluded as well.

The result of this “safe default” however is that jquery.js is a render-blocking resource. So even if you’re doing “inline & defer CSS” your Start-Render time (or one of the variations thereof) will be sub-optimal.

Jonas, the smart guy behind criticalcss.com, proposed to embed inline JS that requires jQuery in a function that executes after the DomContentLoaded event. And so I created a small code snippet as a proof of concept which hooks into Autoptimize’s API and that seems to work just fine;

Add below code to your themes function.php file.

add_action('plugins_loaded','ao_defer_inline_init');

function ao_defer_inline_init() {
if ( get_option('autoptimize_js_include_inline') != 'on' ) {
add_filter('autoptimize_html_after_minify','ao_defer_inline_jquery',10,1);
}
}

function ao_defer_inline_jquery( $in ) {
if ( preg_match_all( '#<script.*>(.*)</script>#Usmi', $in, $matches, PREG_SET_ORDER ) ) {
foreach( $matches as $match ) {
if ( $match[1] !== '' && ( strpos( $match[1], 'jQuery' ) !== false || strpos( $match[1], '$' ) !== false ) ) {
// inline js that requires jquery, wrap deferring JS around it to defer it.
$new_match = 'var aoDeferInlineJQuery=function(){'.$match[1].'}; if (document.readyState === "loading") {document.addEventListener("DOMContentLoaded", aoDeferInlineJQuery);} else {aoDeferInlineJQuery();}';
$in = str_replace( $match[1], $new_match, $in );
} else if ( $match[1] === '' && strpos( $match[0], 'src=' ) !== false && strpos( $match[0], 'defer' ) === false ) {
// linked non-aggregated JS, defer it.
$new_match = str_replace( '<script ', '<script defer ', $match[0] );
$in = str_replace( $match[0], $new_match, $in );
}
}
}
return $in;
}

Your feedback is more than welcome.

original author: Gregor || Code from this Github gist

results:

< PrevPost NextPost >

Start a project

Interested in working together? We should
queue up a chat. I’ll buy the coffee.

Living, learning, & leveling up
one day at a time.

Handcrafted by me © RJ21 Nagour alaa😅

Made with ♥ by

Copyright © Rajesh Royal 2021.