Adding custom attributes to script and stylesheets tags

function custom_attr_style( $html, $handle, $href, $media ) {
    $handles = array('twentyeleven-style'); // stylesheet handle
    if( in_array( $handle, $handles ) ) {
        $html = str_replace(' href=', ' async href=', $html); // added custom attribute
    }
    return $html;
}
add_filter( 'style_loader_tag',  'custom_attr_style', 10, 4 );
 
function custom_attr_script( $html, $handle, $src ) {
	$handles = array('twentyeleven-script'); // script handle
    if( in_array( $handle, $handles ) ) {
        $html = str_replace(' src=', ' async src=', $html); // added custom attribute
    }
    return $html;
}
add_filter( 'script_loader_tag', 'custom_attr_script', 10, 3 );

Leave a Reply

Your email address will not be published. Required fields are marked *