php 如何在WordPress中异步加载CSS文件(使用Scott Jehl的“loadCSS”)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 如何在WordPress中异步加载CSS文件(使用Scott Jehl的“loadCSS”)相关的知识,希望对你有一定的参考价值。

// 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" );
<?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);

// ...
?>

以上是关于php 如何在WordPress中异步加载CSS文件(使用Scott Jehl的“loadCSS”)的主要内容,如果未能解决你的问题,请参考以下文章

如何在父主题css之后加载wordpress子主题css

如何延迟或异步此 WordPress javascript 片段以最后加载以加快页面加载时间?

创建 wordpress 插件时,如何在 jQuery 加载页面中启动挂钩?

如何在WordPress page.php,single.php中加载style.css根目录

Wordpress 插件 - CSS 未加载

Wordpress 文件 functions.php 未加载 style.css