The block of code adds the attribute async
to a array of Javascript files.
Is there a way to check if the files have already have the attribute assigned and if yes, to skip it?
function async_scripts( $tag, $handler, $src ) { /** * An array of JavaScripts files. The value should be the filename. */ $scripts = array( 'script_one.js', 'script_two.js' ); /** * Loop through each file in the $scripts array and add an async option. */ foreach ( $scripts as $script ) { if ( true == strpos( $tag, $script ) ) return str_replace( ' src', ' async src', $tag ); } return $tag; } add_filter( 'script_loader_tag', 'async_scripts', 10, 3 );
I tried looping through global $wp_scripts
however it doesn't appear to work with script_loader_tag
foreach( $wp_scripts->registered as $script ) { if ( ! empty( $script->extra['async'] ) && $script->extra['async'] === true ) { return $tag; }
true == strpos( $tag, $script ) && ! preg_match( '/ async\b/', $tag )
(or usepreg_match( '/<script( .+)? async\b.*?>/', $tag )
) instead of justtrue == strpos( $tag, $script )
..? But then, that's a generic PHP matter..wp_script_add_data( 'theme-navigation', 'async', true );
wp_script_add_data()
itself will not add theasync
attribute, so the theme is likely adding that attribute manually (which you'll have to find out how - what function, hook, file, etc.). But even so, if the simplepreg_match()
failed, then maybe it didn't actually fail, but it never ran for thetheme-navigation
script. So try using a lower priority, i.e. a higher number as the 3rd parameter foradd_filter()
, e.g. 20 as inadd_filter( 'script_loader_tag', 'async_scripts', 20, 3 )
.