How to add defer=”defer” tag in plugin javascripts?

As of WordPress 4.1 there is a filter: script_loader_tag. You can use it to find the correct script:

add_filter( 'script_loader_tag', function ( $tag, $handle ) {

    if ( 'contact-form-7' !== $handle )
        return $tag;

    return str_replace( ' src', ' defer="defer" src', $tag );
}, 10, 2 );

Old answer

There is no dedicated filter available … at least I cannot see one. But …

  • wp_print_scripts() calls WP_Scripts->do_items()
  • which calls WP_Scripts->do_item()
  • which uses esc_url()
  • which does offer a filter: 'clean_url'.

And here we go:

function add_defer_to_cf7( $url )
{
    if ( FALSE === strpos( $url, 'contact-form-7' )
      or FALSE === strpos( $url, '.js' )
    )
    { // not our file
        return $url;
    }
    // Must be a ', not "!
    return "$url' defer="defer";
}
add_filter( "clean_url', 'add_defer_to_cf7', 11, 1 );

Caveat: not tested, just an idea. 🙂

Update

I have written and tested a plugin with this code.

Leave a Comment