1

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;
            }
4
  • How about checking for true == strpos( $tag, $script ) && ! preg_match( '/ async\b/', $tag ) (or use preg_match( '/<script( .+)? async\b.*?>/', $tag )) instead of just true == strpos( $tag, $script ) ..? But then, that's a generic PHP matter..
    – Sally CJ
    Feb 26, 2022 at 17:10
  • @SallyCJ - I considered that however it's not matching for some odd reason. It matches other attributes. The theme appears to be adding the async attribute with wp_script_add_data( 'theme-navigation', 'async', true );
    – Motivated
    Feb 26, 2022 at 17:43
  • wp_script_add_data() itself will not add the async 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 simple preg_match() failed, then maybe it didn't actually fail, but it never ran for the theme-navigation script. So try using a lower priority, i.e. a higher number as the 3rd parameter for add_filter(), e.g. 20 as in add_filter( 'script_loader_tag', 'async_scripts', 20, 3 ).
    – Sally CJ
    Feb 28, 2022 at 9:34
  • (If lowering the priority doesn't work, you can try my new regex here..)
    – Sally CJ
    Feb 28, 2022 at 9:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.