Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
How to load CSS files asynchronously in WordPress (using Scott Jehl's "loadCSS")
// This is the cleaner code per request of a thread in the LinkedIn group "WordPress"
// ...
// register and enqueue loadCSS
function load_scripts_and_styles() {
// register loadCSS
wp_register_script( 'load-css-async', get_stylesheet_directory_uri() . '/path/to/js/loadCSS.js', array(), '', false );
// enqueue loadCSS
wp_enqueue_script( 'load-css-async' );
add_action('wp_enqueue_scripts', 'load_scripts_and_styles', 999);
// ...
// This is the cleaner code per request of a thread in the LinkedIn group "WordPress"
// this is a modified file for demonstration purposes
// original repository
loadCSS: load a CSS file asynchronously.
[c]2014 @scottjehl, Filament Group, Inc.
Licensed MIT
function loadCSS( href, before, media ){
"use strict";
var ss = window.document.createElement( "link" );
var ref = before || window.document.getElementsByTagName( "script" )[ 0 ];
ss.rel = "stylesheet";
ss.href = href; = "only x";
ref.parentNode.insertBefore( ss, ref );
setTimeout( function(){ = media || "all";
} );
return ss;
// here's where you specify the CSS files to be loaded asynchronously
// load Google Web Font
loadCSS( "|Open+Sans" );
// load Font Awesome from CDN
loadCSS( "//" );
// load a local CSS file
loadCSS( "http://yourserver.tld/path/to/your/css/file.css" );

This comment has been minimized.

Copy link

tarranjones commented Mar 9, 2016

Instead of specifying the CSS files individually you could hook into style_loader_tag like so.

function add_load_css(){ 
    readfile(get_stylesheet_directory() . '/js/loadCSS.js'); 
add_filter('style_loader_tag', 'link_to_loadCSS_script',9999,3);
function link_to_loadCSS_script($html, $handle, $href ) {
    $dom = new DOMDocument();
    $a = $dom->getElementById($handle.'-css');
    return "<script>loadCSS('" . $a->getAttribute('href') . "',0,'" . $a->getAttribute('media') . "');</script>\n";

This comment has been minimized.

Copy link

jedixraja commented Jul 18, 2017

i dont understand. please help me, my site is


This comment has been minimized.

Copy link

Nadareh commented Oct 5, 2017

Hi there,

This is really great! It help me a lot. I was just thinking if there's a way to do this on mobile? I was able to rank up the score to 95/100 on Desktop but the mobile is still score is still very low.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.