【问题标题】:WordPress enqueuing a CSS file using JavaScript inside Functions.phpWordPress 在 Functions.php 中使用 JavaScript 将 CSS 文件排队
【发布时间】:2021-04-27 20:44:09
【问题描述】:

我正在尝试仅在移动设备上加载 CSS 文件。

我做了一些研究,发现最好的方法是使用 JS,所以这是我找到的代码:

$( document ).ready(function() {      
var isMobile = window.matchMedia("only screen and (max-width: 760px)");

if (isMobile.matches) {
    //Add your script that should run on mobile here
}
});

现在如何将下面的代码放入该代码中?

wp_enqueue_style( 'custom-css', get_template_directory_uri() . '/responsive.css'    );

还有如何将它包含在 Functions.php 文件中。

我尝试了以下方法,但没有成功

?>
<script>
$( document ).ready(function() {      
var isMobile = window.matchMedia("only screen and (max-width: 760px)");

if (isMobile.matches) {

wp_enqueue_style( 'custom-css', get_template_directory_uri() . '/responsive.css'    );
    
}
});
</script>
<?php

【问题讨论】:

  • wp_enqueue_style 是在服务器上运行的 php 函数。
  • 我认为你应该重新考虑你的方法。您在 JS 中使用 CSS 媒体查询来使用 PHP 有条件地加载文件,为什么要跳过这么多圈?只需将该媒体查询添加到您的 CSS 文件即可。
  • @prieber 确实,这是我在问题帖子中尝试的一种愚蠢方法。只是一个试图学习东西的新手 :) 我希望有一个单独的 CSS 文件只能在移动设备上加载,我正在尝试优化我的网站速度,这就是我尝试这种方法的原因。但不用担心,下面的最佳答案就是我想要的。
  • @user3152370 如果您正在尝试优化,那么我建议您先使用移动设备,当屏幕变大时加载任何后续 CSS 文件。移动数据对某些人来说仍然是一种商品,因此节省的每一字节数据都可以获利。

标签: javascript wordpress php-enqueue wp-enqueue-scripts


【解决方案1】:

结合 PHP 和 JavaScript 是不可能的。 PHP 只在服务器上运行,而 JavaScript 只在客户端上运行(有一些例外)。

使用wp_enqueue_style 函数的最后一个参数来设置wp_enqueue_style 函数创建的&lt;link&gt; 标记上的media 属性。 MDN 对media 属性有如下说明:

您还可以在媒体属性中提供媒体类型或查询;仅当媒体条件为真时才会加载此资源。

此属性指定链接资源适用的媒体。它的值必须是媒体类型/媒体查询。此属性主要在链接到外部样式表时有用——它允许用户代理为其运行的设备选择最适合的样式表。

Source

这意味着您可以在media 属性中进行媒体查询。如果该媒体查询匹配,则将加载样式表。

<?php
add_action( 'wp_enqueue_scripts', 'add_responsive_style' );
function add_responsive_style() {
  wp_enqueue_style( 
    'responsive', // Handle.
    get_template_directory_uri() . '/responsive.css', // Path to file.
    [], // Dependencies.
    false, // Version number.
    'screen and (max-width: 760px)' // <-- Media.
  );
}
?>

这将输出:

<link href="yourtheme/responsive.css" rel="stylesheet" media="screen and (max-width: 760px)">

【讨论】:

    猜你喜欢
    • 2018-05-03
    • 2014-10-26
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 2016-03-09
    • 2014-05-29
    • 1970-01-01
    相关资源
    最近更新 更多