DEV Community

Cover image for Fixed Render-blocking JQuery in WordPress with Autoptimize
Rajesh Royal
Rajesh Royal

Posted on • Originally published at rajeshroyal.com on

Fixed Render-blocking JQuery in WordPress with Autoptimize

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. This code will replace all the $(document).ready() with Js native DOMContentLoaded event listener.

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;
}
Enter fullscreen mode Exit fullscreen mode

Now you can load jQuery defer or async on your site.
Your feedback is more than welcome.

original author: Gregor || Code from this Github gist

results:

fix render blocking jquery in wordpress google page speed insight php code github gist

The post Fixed Render-blocking JQuery in wordpress with Autoptimize appeared first on Rajesh Royal.

Top comments (1)

Collapse
 
aliahmarix profile image
Ali Ahmari

Thanks for sharing this.
I was wondering if you could tell me how I can fix Render-blocking problem for WordPress jquery.js file with lscache plugin.