Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
POC to defer inline JS that requires jQuery
<?php
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;
}
@SciLor

This comment has been minimized.

Copy link

SciLor commented Feb 6, 2019

Works great. for me. I had to add recaptcha to make it work.

@figarro

This comment has been minimized.

Copy link

figarro commented Oct 31, 2019

Is there a way to hook add_filter to something that's WordPress native and does not depend on the Autoptimize plugin?

@futtta

This comment has been minimized.

Copy link
Owner Author

futtta commented Oct 31, 2019

I don't think WordPress native has a filter for the full HTML @figgaro, but if you're using a page caching plugin then that probably has a filter that allows the same.

@niamrox

This comment has been minimized.

Copy link

niamrox commented Apr 30, 2020

Did not work for me !

@roytuts

This comment has been minimized.

Copy link

roytuts commented May 27, 2020

Did not work for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.