【问题标题】:Load CSS file only if element with class is present on the page仅当页面上存在具有类的元素时才加载 CSS 文件
【发布时间】:2019-04-10 13:53:48
【问题描述】:

我正在尝试优化 CSSS 文件的加载,因为我正在将一些大型 CSS 文件加载到不使用它们的页面上。有没有办法让我只在该页面上存在带有类的元素时才将它们排入队列。

我尝试了以下方法,但它不起作用:

jQuery(document).ready(function($) {
    //Script Checkers
    var wowJS = $('.wow');

    if (wowJS.length > 0) {
        $.getScript('/wp-content/themes/gowebsites/gw-addon/js/wow.js', function() {
            new WOW().init();
        });

        var head = document.getElementsByTagName('head')[0];
        var cssNode = document.createTextNode("link");

        cssNode.href = "/wp-content/themes/gowebsites/gw-addon/css/animations.css";
        cssNode.rel = "stylesheet";
        //console.log("CSS Node: "+cssNode); = [object Text]

        head.appendChild(cssNode);
    }
});

我已经看到了用于将 css 文件添加到头部的函数,但是它们都不允许有条件的能力。

编辑:我刚刚使用了 getScripts() jQuery 函数,但我仍然需要知道如何仅在需要时将 css 添加到标题中。

编辑:供任何人将来参考,这是最终的工作代码:

jQuery(document).ready(function($) {
    //Script Checkers
    var wowJS = $('.wow');

    if (wowJS.length > 0) {
        $.getScript('/wp-content/themes/gowebsites/gw-addon/js/wow.js', function() {
            new WOW().init();
        });

        var head = document.getElementsByTagName('head')[0];
        var cssNode = document.createElement("link");

        cssNode.href = "/wp-content/themes/gowebsites/gw-addon/css/animations.css";
        cssNode.rel = "stylesheet";

        head.appendChild(cssNode);
    }
});

【问题讨论】:

  • appendChild() 接受新的节点或元素,而不是字符串。另请注意,如果您在页面中包含 jQuery,您可以使用 $.getScript() 简化此操作
  • 我也试过只追加,没有成功
  • 关于 wp_enqueue 的想法是错误的。您将根据使该类在页面中可用的任何条件有条件地排队。不确定是类别、使用的页面模板、内容相关等
  • 唯一的条件是使用了一个简码并且存在一个具有类的元素,我认为这在 php 中不是最好的或最有能力的?

标签: javascript php jquery wordpress


【解决方案1】:

先创建节点,然后使用appendChild() 方法追加,例如:

var scriptNode = document.createElement("script");
scriptNode.src = "/wp-content/themes/gowebsites/gw-addon/js/wow.js";

var cssNode = document.createElement("link");
cssNode.href = "/wp-content/themes/gowebsites/gw-addon/css/animations.css";
cssNode.rel = "stylesheet";

head.appendChild(scriptNode);
head.appendChild(cssNode);

【讨论】:

  • 我是否希望在页脚中加载一个脚本,如何将页脚区域附加到结束正文标记内?
  • body 节点上调用appendChild() 而不是head
  • 正如@RoryMcCrossan 所说,您只需要指定元素
  • 我已经用我当前的代码更新了我的答案,它不会创建或链接元素。我已经使用 alert() 来检查它返回“1”的 wowJS 的值
  • createElement 确实修复了它,没有收到您的评论通知,我自己偶然发现了答案,哈哈
【解决方案2】:

你应该使用insertAdjacentHTML

head.insertAdjacentHTML("afterend",'<script language="javascript" src="/wp-content/themes/gowebsites/gw-addon/js/wow.js"></script>');
head.insertAdjacentHTML("afterend",'<link href="/wp-content/themes/gowebsites/gw-addon/css/animations.css" rel="stylesheet">');

【讨论】:

    猜你喜欢
    • 2011-08-13
    • 1970-01-01
    • 2019-05-31
    • 2016-02-17
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    相关资源
    最近更新 更多