入队、注册和使用 Wordpress 加载 CSS 和 JavaScript [英] Enqueue, Register & Load CSS and JavaScript with Wordpress

查看:26
本文介绍了入队、注册和使用 Wordpress 加载 CSS 和 JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 WordPress 的初学者,在 WordPress 中,有没有办法在页面被调用时将 JS/CSS 文件加载到特定页面,而不是在另一个页面上加载它?

I'm a beginner in WordPress, in WordPress is there a way to load JS/CSS file to a specific page, when page is called, and not to load it on an other one?

推荐答案

function.php 文件中加载 scriptsstylesheet 是 <强>最佳实践与 Wordpress.

Loading scripts and stylesheet from the function.php file is the best practice with Wordpress.

向 WordPress 添加脚本和样式是一个相当简单的过程.本质上,您将创建一个函数,将您所有的脚本和样式.

Adding scripts and styles to WordPress is a fairly simple process. Essentially, you will create a function that will enqueue all of your scripts and styles.

来源@https://developer.wordpress.org/themes/basics/include-css-javascript/

使用 Wordpress,您可以在实际排队之前注册 scriptstylesheet.我们使用一些非常方便的函数,称为 wp_register_script/wp_register_style 用于 scriptswp_enqueue_script/wp_enqueue_style> 用于 样式表.你应该注意并阅读函数参数

With Wordpress you can register a script and stylesheet before actually enqueuing it. We use some really handy functions called wp_register_script / wp_register_style for scripts and wp_enqueue_script / wp_enqueue_style for stylesheet. You should pay attention and read about the functions arguments

与一些条件标签和函数一起,我们最终构建了非常复杂的行为,以便在我们的主题和页面上有条件地注册和排队 scriptsstylesheet.您应该注意并阅读函数参数.

Together with some conditional tags and functions we end up building really complex behaviours to conditionally register and enqueue scripts and stylesheet on our theme and pages. You should pay attention and read about the functions arguments.

可以在模板文件中使用条件标签来更改显示内容以及该内容如何显示在特定的页面取决于页面匹配的条件.

The Conditional Tags can be used in your Template files to change what content is displayed and how that content is displayed on a particular page depending on what conditions that page matches.

来源@https://codex.wordpress.org/Conditional_Tags

例如 is_home()is_search()is_single()is_page()... 可用于在我们的不同页面上有条件地注册和排队 scriptsstylesheet.

For example is_home(), is_search(), is_single() or is_page()... can be used to conditionally register and enqueue scripts and stylesheet on our different pages.

<?php
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
  if( ! is_admin() ) {

    /**
    * Register then enqueue jquery_js
    * @link https://developer.wordpress.org/reference/functions/wp_register_script/
    * @link https://developer.wordpress.org/reference/functions/wp_enqueue_script/
    */
    wp_register_script( 'jquery_js', trailingslashit( get_template_directory_uri() ) . 'assets/js/jquery-3.5.1.min.js', array(), '3.5.1', true );
    wp_enqueue_script( 'jquery_js' );
  };
}; ?>

在这个例子中,如果我们在与管理员的页面不同的页面上,我们只想将我们的 jquery-3.5.1.min.js 加入队列,使用 if ( !is_admin())....

In this example we only want to enqueue our jquery-3.5.1.min.js if we are on a different page than an admin's one, using if ( ! is_admin() )....

scriptstylesheet 可以托管在本地或不同的服务器上(例如:CDN).使用 CDN 时,我们要确保源可用.我们可以使用 @fopen(); 来确保 CDN 可访问,如果不能,则提供后备:

script and stylesheet can be hosted locally or on a different server (eg: CDNs). When using CDNs, we want to make sure that the source is available. We can use @fopen(); to make sure the CDN is reachable, and if not, serve a fallback:

<?php
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
  if( ! is_admin() ) {

    /**
    * Register then enqueue jquery_js
    * @link https://developer.wordpress.org/reference/functions/wp_register_script/
    * @link https://developer.wordpress.org/reference/functions/wp_enqueue_script/
    *
    * Check if CDN's url is valid, if not return fallback
    * @link https://www.php.net/manual/en/function.fopen.php
    */
    $test_jquery_js = @fopen( 'https://code.jquery.com/jquery-3.5.1.min.js', 'r' );
    if( $test_jquery_js !== false ) {
      wp_register_script( 'jquery_js', '//code.jquery.com/jquery-3.5.1.min.js', array(), '3.5.1', true );
    } else {
      wp_register_script( 'jquery_js', trailingslashit( get_template_directory_uri() ) . 'assets/js/jquery-3.5.1.min.js', array(), '3.5.1', true );
    };
    wp_enqueue_script( 'jquery_js' );
  };
}; ?>


添加属性(例如:Crossorigin、Integrity)

有时需要向 scriptstylesheet 标签添加属性,以正确地将它们排入队列.使用 script_loader_tagstyle_loader_tag 钩子,我们可以做到:


Adding Attributes (eg: Crossorigin, Integrity)

Sometimes it is required to add attributes to script and stylesheet tags, to properly enqueue them. Using the script_loader_tag or style_loader_tag hook, we can do just that:

<?php
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
  if( ! is_admin() ) {

    /**
    * Register then enqueue jquery_js
    * @link https://developer.wordpress.org/reference/functions/wp_register_script/
    * @link https://developer.wordpress.org/reference/functions/wp_enqueue_script/
    *
    * Check if CDN's url is valid, if not return fallback
    * @link https://www.php.net/manual/en/function.fopen.php
    *
    * Add rel='preload' <link> and required attributes to jquery_js
    * Filters the HTML link tag of an enqueued style & add required attributes
    * @link https://developer.wordpress.org/reference/hooks/script_loader_tag/
    */
    $test_jquery_js = @fopen( 'https://code.jquery.com/jquery-3.5.1.min.js', 'r' );
    if( $test_jquery_js !== false ) {
      wp_register_script( 'jquery_js', '//code.jquery.com/jquery-3.5.1.min.js', array(), '3.5.1', true );
    } else {
      wp_register_script( 'jquery_js', trailingslashit( get_template_directory_uri() ) . 'assets/js/jquery-3.5.1.min.js', array(), '3.5.1', true );
    };
    wp_enqueue_script( 'jquery_js' );

    add_filter( 'script_loader_tag', 'data_jquery_js', 10, 3 );
    function data_jquery_js( $tag, $handle, $src ) {
      if( $handle === 'jquery_js' ) {
        $integrity = 'sha256...';
        $tag = str_replace(
          array(
            "<script",
            "></script>",
          ),
          array(
            "<link rel='preload prefetch' href='" . esc_url( $src ) . "' as='script' integrity='" . $integrity . "' crossorigin='anonymous' />" . PHP_EOL . "<script",
            "integrity='" . $integrity . "' crossorigin='anonymous' async></script>",
          ),
          $tag
        );
      };
      return $tag;
    };
  };
}; ?>

在这里,我们添加了 preload 链接标签、crossoriginintegrityasync 属性.

Here, we are adding a preload link tag, the crossorigin, integrity and the async attribute.

如果您不需要在入队之前注册您的 scriptstylesheet,您实际上可以忽略它.例如:

If you don't need to register your script or stylesheet prior to enqueuing it, you can actually ignore it. eg:

wp_enqueue_script( 'jquery_js', trailingslashit( get_template_directory_uri() ) . 'assets/js/jquery-3.5.1.min.js', array(), '3.5.1', true  );

这里我们不注册我们的脚本并直接跳转到入队.

Here we don't register our script and jump straight to the enqueue.

对于 Wordpress,jQuery 通常是预先注册的,并带有核心.如果你想加入你自己的版本,你必须注销核心 jQuery 版本.

With Wordpress, jQuery is normally pre-registered, and comes with the core. If you want to enqueue your own version you MUST deregister the core jQuery version.

<?php
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
  if( ! is_admin() ) {

    /**
    * Deregister Wordpress jquery core version
    * @link https://developer.wordpress.org/reference/functions/wp_deregister_script/
    */
    wp_deregister_script( 'jquery' );

    //...here goes the rest of your function...
  };
}; ?>


在管理端入队并注册scriptstylesheet

使用 admin_enqueue_scripts 操作挂钩,您可以做到这一点.


Enqueue and register a script or stylesheet on the admin side

Using the admin_enqueue_scripts action hook, you can do just that.

<?php
do_action( 'admin_enqueue_scripts', 'admin_scripts' );
function admin_scripts() {
  //...here goes the rest of your function...
}; ?>


了解详情

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆