I am deferring JS scripts in order to optimize page load times and SEO. My code to defer scripts is something like:
add_filter(
'script_loader_tag', // Filters the HTML script tag of an enqueued script.
function ( $tag, $handle ) {
return str_replace( ' src', ' defer="defer" src', $tag );
}
);
It works fine for most scripts. However, when it defers scripts like wp-i18n
, it causes the error because of the -js-after
code that it tries to run before the it executes the deferred script.
<script type='text/javascript' defer="defer" src='http://192.168.1.71/wp-includes/js/dist/i18n.min.js?ver=db9a9a37da262883343e941c3731bc67' id='wp-i18n-js'></script>
<script type='text/javascript' id='wp-i18n-js-after'>
wp.i18n.setLocaleData( { 'text direction\u0004ltr': [ 'ltr' ] } );
</script>
It seems the problem is that the script is deferred in contrast to its -js-after
script. I need a solution that does one of the following.
- Skips deferring scripts that have a
-js-after
- Deferrs the
js-after
along with the script.
Implementing the first option using using
$data = $wp_scripts->get_data( 'wp-i18n', 'data' );
does not work because $data does not contain information as to whether the script has a -js-after
. Searching for "detecting 'WordPress -js-after'" does not give any helpful results.
js-after
isn't what you should be looking for, these look to be scripts added viawp_add_inline_script
. Can an inline script even be deferred? I don't think it makes sense$assets[] = new GF_Script_Asset( 'wp-a11y' );
inform_display.php
.wp-i18n
is a dependency ofwp-a11y
. Therefore it comes outwp-i18n
is enqueued on the frontend when there is a form display.wp_add_inline_script()
/wp_localize_script()
inline dependencies by digging through the registry in the$wp_scripts
global, probably at both thewp_print_scripts
action as well aswp_footer
.