Following Keith Clarks advice, i’d like to load my fonts asynchronously. I try to achieve that by adding:
wp_enqueue_style( 'font-awesome', URI . '/fonts/font-awesome/css/font-awesome.min.css' );
wp_style_add_data( 'font-awesome', 'onload', 'if(media!=\'all\')media=\'all\'');
to my scripts.php
file, but apparently this argument is not well taken by that function, because there is no onload attribute. How properly can I do that in WordPress?
3 Answers
We can use style_loader_tag
filter to filter the link that is being output.
Here is the filter:
$tag = apply_filters( 'style_loader_tag', "<link rel="$rel" id='$handle-css' $title href="https://wordpress.stackexchange.com/questions/231597/$href" type="text/css" media="$media" />\n", $handle, $href, $media);
Here the link $handle for which you want to add attribute is font-awesome
so if the handle, so you can replace font-awesome-css
with extra info.
add_filter('style_loader_tag', 'wpse_231597_style_loader_tag');
function wpse_231597_style_loader_tag($tag){
$tag = preg_replace("/id='font-awesome-css"https://wordpress.stackexchange.com/", "id='font-awesome-css' online=\"if(media!='all')media="all"\"", $tag);
return $tag;
}