Last active
February 23, 2023 18:53
-
-
Save schilke/02357d9263ed28fc1769 to your computer and use it in GitHub Desktop.
How to load CSS files asynchronously in WordPress (using Scott Jehl's "loadCSS")
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// 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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 https://github.com/filamentgroup/loadCSS/ | |
/*! | |
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; | |
ss.media = "only x"; | |
ref.parentNode.insertBefore( ss, ref ); | |
setTimeout( function(){ | |
ss.media = media || "all"; | |
} ); | |
return ss; | |
} | |
// here's where you specify the CSS files to be loaded asynchronously | |
// load Google Web Font | |
loadCSS( "http://fonts.googleapis.com/css?family=Lato|Open+Sans" ); | |
// load Font Awesome from CDN | |
loadCSS( "//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" ); | |
// load a local CSS file | |
loadCSS( "http://yourserver.tld/path/to/your/css/file.css" ); |
i dont understand. please help me, my site is https://naijadown.com
https://sa.wikiwaparz.com
https://mp3.wikiwaparz.com
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.
Thanks!
Hello,
Sorry I'm a beginner :)
are these functions safe to use? doesn't it have any security issue or web browser support problem?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Instead of specifying the CSS files individually you could hook into
style_loader_tag
like so.