【问题标题】:How to load CSS asynchronously - WordPress如何异步加载 CSS - WordPress
【发布时间】:2018-09-18 11:54:19
【问题描述】:

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

here获得源码

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' );

}

【问题讨论】:

  • 是否有控制台错误信息?或者这只是悄悄地失败了?
  • 控制台没有错误
  • 我在控制台中检查的脚本没有错误。 'load_script_and_styles()' 函数有错误
  • 您是在尝试将 load_scripts_and_styles() 作为 JavaScript 还是 PHP 执行?
  • 使用 add_action .. add_action( 'wp_enqueue_scripts', load_scripts_and_styles', 100 );

标签: javascript css wordpress


【解决方案1】:

您的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");

【讨论】:

  • 是的!试过问题不在于脚本。问题在于 wp_enqueue_script。你发现 wp_enqueue_script 有什么错误吗?
  • 似乎http://fonts.googleapis.com 字体已包含在您的主题中。这是问题。
  • 但其他 CSS 也没有加载
猜你喜欢
  • 1970-01-01
  • 2011-07-08
  • 2018-01-06
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
相关资源
最近更新 更多