WordPress introduces two methods of css/js

The introduction of css/js in WordPress  is the first difficulty we face when making themes. Any theme must load its own css, js, and it may even need to load Jquery files. There are many online methods and different opinions. We Today, learn from the latest twentysixteen theme of WordPress official to learn and summarize the various common methods of WordPress introducing css/js, and the most optimized loading method.

In fact, the N methods on the Internet can be summed up in two ways:
1. Directly import the file in the template file header.php
2. Load the JS file through the WP's own function in the theme functions.phpwp_enqueue_scripts , wp_enqueue_styleand load the Css style through it.

1. Import files directly in the template file header.php

1. The best way to understand, the most straightforward, and the worst way to directly import the file in the template file header.php

<script type='text/javascript' src='http://www.jquery.com/js/jquery/1.10.2/jquery-1.10.2.min.js'></script>
<script type='text/javascript' src='http://www.511yj.com/css/bootstrapwp.js'></script>
<link rel="stylesheet" href="http://www.511yj.com/css/bootstrapwp.css">

If you think this is boring, you can still do this

<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/style.css">
<script src="<?php echo get_template_directory_uri(); ?>/bootstrap/js/bootstrap.js"></script>

get_template_directory_uri()Obtain the theme directory through the function echooutput.
注意啦Although the following method is placed in functions.php, the surface feels better...

";
}
 add_action( 'wp_head', 'add_stylesheet_to_head' );
 ?>

But WordPress cannot determine whether the JS and Css files are loaded on the page. If another plugin uses the same JS and Css files, it cannot check whether the JS and Css files have been included in the page. Then the plug-in loads the same file a second time, resulting in duplicate codes and slower response speed.

2. Introduction of WordPress optimization solutions: registration and queuing

1. Register
wp_register_style() function to register:

<?php wp_register_style( $handle, $src, $deps, $ver, $media ); ?>

Parameters:
$handle (string, required) is the unique name of your style sheet. Other functions will use this "handle" to queue and print the style sheet.
$src(String, required) refers to the URL of the style sheet. You can use functions such as get_template_directory_uri() to get the style files in the theme directory. Never think about hard coding!
$deps (Array, optional) Process the names of related styles. If you lose some other style files, your style sheet will not work properly. You can use this parameter to set the "dependency".
$ver (String or boolean, optional) version number. You can use the version number of your theme or any one you want. If you do not wish to use a version number, set it to null. The default is false, which makes WordPress add its own version number.
$media (String, optional) refers to the media type of CSS, such as "screen" or "handheld" or "print". If you don't know if you need to use this, then don't use it. The default is "all".
example:

wp_register_style(
    'my-bootstrap-extension', // 名称
    get_template_directory_uri() . '/css/my-bootstrap-extension.css', // 样式表的路径
    array( 'bootstrap-main' ), // 依存的其他样式表
    '1.2', // 版本号
    'screen', // CSS 媒体类型
);

wp_register_style() function to register:

<?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer ); ?>

Parameter
$handle (string) (required) script name. Lowercase string. Default value: None
$src(string) (optional) Example of script path in WordPress root directory: "/wp-includes/js/scriptaculous/scriptaculous.js". This parameter is only used when WordPress does not understand the script. Default value: None
$deps(array) (optional) an array of handles that the script depends on; other scripts that need to be loaded before loading the script. If there is no dependency, return false. This parameter is only used when WordPress does not understand the script. Default: array()
$ver(string) (optional) A string indicating the version number of the script (if a version number exists). The default is false. This parameter can ensure that the correct version is still sent to the client even when caching is enabled, so if the version number is available and meaningful to the script, include the version number. Default value: false
$in_footer(Boolean) (optional) Usually the script will be placed in the block. If the function is true, the script will appear at the bottom of the block. The theme is required to include the wp_footer() hook in the appropriate location. (New features of WordPress) Default value: false
Example:

<?php
function my_enqueue_scripts() {
if( !is_admin ) { // 前台加载的脚本与样式表
// 去除已注册的 jquery 脚本
wp_deregister_script( 'jquery' );
// 注册 jquery 脚本
wp_register_script( 'jquery', get_template_directory_uri() . '/js/jquery.js', false, '1.0', false );
// 提交加载 jquery 脚本
wp_enqueue_script( 'jquery' );
 } 
} 
// 添加回调函数到 init 动作上
add_action( 'init', 'my_enqueue_scripts' );
?>

When there are a lot of css/js and need to be loaded in different situations, you need to use wp_register_script()and wp_register_style()functions, which can better manage resources and avoid duplication of work. In the following sample code, first register all the style sheets that need to be used on the init action, and then no matter where you want to import it, you can simply load it with wp_enqueue_style( $handle ).

// 在init action处注册脚本,可以与其它逻辑代码放在一起
function my_init(){
    $url = get_template_directory_uri();
    // 注册样式表
    $styles = array(
        'style1' => $url . '/css/style1.css',
        'style2' => $url . '/css/style2.css',
        'style3' => $url . '/css/style3.css'
    );
     foreach( $styles as $k => $v ){
        wp_register_style( $k, $v, false );
    } 
    // 注册脚本     
    // 其它需要在init action处运行的脚本
}
add_action( 'init', 'my_init' );

The script needs to be run when registering the script $wp_scripts->add( $handle, $src, $deps, $ver );. If the script is not registered and used directly wp_enqueue_script, the add method needs to be called first. That is to say, repeating a script will run the add method multiple times, which reduces the efficiency of the program.
In WordPress, the registered style is "optional". If your style will not be used by other plugins, or you don't plan to use any code to load it again, you are free to queue styles without registering it. Continue to see how it is achieved.
2. The queuing
wp_register_style()  function is not mandatory. I want to tell you that you can use it in two different ways wp_enqueue_style():

<?php
 // 如果我们之前已经注册过样式
wp_enqueue_style( 'my-bootstrap-extension' ); 
// 如果我们之前没有注册,我们不得不设置 $src 参数!
wp_enqueue_style(
    'my-bootstrap-extension',
    get_template_directory_uri() . '/css/my-bootstrap-extension.css',
    array( 'bootstrap-main' ),
    null, // 举例不适用版本号
    // ...并且没有指定CSS媒体类型
); 
?>

Remember: If a plug-in will use your stylesheet, or you plan to load it in different places in your theme, you should definitely register it first.
3. Load the style to our website.
We can't use the wp_enqueue_style() function anywhere in the theme-we need to use the "action" hook. There are also three action hooks that we can use for various purposes:
wp_enqueue_scripts to load scripts in the foreground of the website and CSS
admin_enqueue_scripts to load scripts in the background and CSS
login_enqueue_scripts to load scripts and CSS on the WP login page.
Here are examples of these hooks:

<?php
 // 在网站前台加载css
function mytheme_enqueue_style() {
    wp_enqueue_style( 'mytheme-style', get_stylesheet_uri() ); 
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_style' ); 
// 在后台加载css
function mytheme_enqueue_options_style() {
    wp_enqueue_style( 'mytheme-options-style', get_template_directory_uri() . '/css/admin.css' ); 
}
add_action( 'admin_enqueue_scripts', 'mytheme_enqueue_options_style' );
 
// 在登录页面加载css
function mytheme_enqueue_login_style() {
    wp_enqueue_style( 'mytheme-options-style', get_template_directory_uri() . '/css/login.css' ); 
}
add_action( 'login_enqueue_scripts', 'mytheme_enqueue_login_style' );
 ?>

4. Another function:wp_print_scripts()
Although loading JavaScript files at the end of the page is very helpful for page loading speed, please note that the so-called end of the page refers to a wp_footer() function called in WordPress  , which is usually just before the label of the page (Of course it is the end).
Sometimes we may need to use some JavaScript before the wp_footer function appears, such as the jquery.js file.
This situation is also very common. For example, I created a separate link page, in which I used the jQuery method to get the favicon of the linked website. Obviously, I only need to use this part of the code on this only page, so it is best to put this code directly in this page template.
Here comes the problem: this part of the content obviously appeared before wp_footer, then this code appeared before the jquery.js file, causing the code segment to actually not work, because the code segment that calls the jQuery method must be larger than jquery.js Load after the file.
So how to deal with this special situation? It's actually very simple. Take the above scenario as an example, since we need to call the jquery.js file first, then we directly output the required jquery.js file before the code segment, instead of using  wp_enqueue_script() functions, use wp_print_scripts() functions instead .
wp_enqueue_script() The  wp_print_scripts() difference is: wp_enqueue_script() tell WordPress "I need to use a JavaScript file on this page, you have to remember to load ah." WordPress is processed in wp_head() by default, but we changed it to wp_footer().wp_print_scripts() Then directly output the required JavaScript file at the location where you use this method, instead of adding it to the processing task of WordPress.
If we use it in the middle of the page,

 <?php wp_print_scripts('jquery'); ?>

Directly output the jquery.js file (usually its compressed version jquery.min.js), then even if other plugins or something use it,

 <?php wp_enqueue_script('jquery'); ?>

Tell WordPress that jquery.js needs to be loaded. When WordPress is processed in wp_footer(), it will first check whether it already has it before. If it does, it will not reload it again.
5. Some additional functions
WordPress has some very useful functions about CSS: they allow us to print embedded styles, view the queue status of style files, add metadata, and log out styles.
Add dynamic inline style:wp_add_inline_style()
If your theme has options to customize the style of the theme, you can use the wp_add_inline_style() function to print the built-in style:

function mytheme_custom_styles() {
    wp_enqueue_style( 'custom-style', get_template_directory_uri() . '/css/custom-style.css' );
    $bold_headlines = get_theme_mod( 'headline-font-weight' ); // 比方说,它的值是粗体“bold”
    $custom_inline_style = '.headline { font-weight: ' . $bold_headlines . '; }';
    wp_add_inline_style( 'custom-style', $custom_inline_style );
}
add_action( 'wp_enqueue_scripts', 'mytheme_custom_styles' );

Convenient. But remember: you must use the same hadle name as the inline style sheet to be added later.
Add metadata to stylesheet:wp_style_add_data()
wp_style_add_data()  is a great function, it allows you to add metadata to your style, including conditional comments, RTL support and more!

<?php
// wp_style_add_data() 示例
function mytheme_extra_styles() {
    wp_enqueue_style( 'mytheme-ie', get_template_directory_uri() . '/css/ie.css' );
    wp_style_add_data( 'mytheme-ie', 'conditional', 'lt IE 9' );
    /*
     * alternate usage:
     * $GLOBALS['wp_styles']->add_data( 'mytheme-ie', 'conditional', 'lte IE 9' );
     * wp_style_add_data() is cleaner, though.
     */
} 
add_action( 'wp_enqueue_scripts', 'mytheme_ie_style' ); 
?>

Articles you may be interested in:


▪  Replace your Wordpress menu with Bootstrap menu style

▪ The  most complete and best wordpress plugin summary recommendation

▪  Wordpress uses Redis cache acceleration | 511 met strongly recommended

▪  Detailed explanation of WordPress database and table structure function

▪  WordPress single page displays article list in categorized form

▪  Add a random article to the WordPress backend widget

▪  query_posts displays the posts with the specified ID in your sidebar

▪  WordPress background can not log in, there is an endless loop solution

▪  Examples of using Redux Framework, the best back-end framework for Wordpress

▪  WordPress allows your web pages to display different logos

Guess you like

Origin blog.csdn.net/zcp528/article/details/108658102