如何异步加载CSS - WordPress

时间:2018-04-09 06:41:30

标签: javascript css wordpress

我正在尝试异步加载CSS,但下面的代码未加载CSS。为什么?

从[{3}}

获取来源
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");

功能:

function load_scripts_and_styles() {

    // register loadCSS
    wp_register_script( 'load-css-async', get_stylesheet_directory_uri() . '/loadCSS.js', array(), '', false );

    // enqueue loadCSS
    wp_enqueue_script( 'load-css-async' );

}

1 个答案:

答案 0 :(得分:0)

您的http://fonts.googleapis.com尝试使用其他css文件时似乎有问题。似乎工作正常。

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

loadCSS("http://localhost/demowp/wp-content/themes/sydney/css/file.css");