简体   繁体   English

wp_register_style()和wp_enqueue_style之间的区别

[英]Difference between wp_register_style() and wp_enqueue_style

I'm new to WordPress development. 我是WordPress开发的新手。 While going through some example codes I came across wp_register_style() , used to register a stylesheet and its location which can be called later using wp_enqueue_style() . 在查看一些示例代码时,我遇到了wp_register_style() ,用于注册样式表及其位置,以后可以使用wp_enqueue_style()进行调用。

But going through the documentation of wp_enqueue_style() , it says "Registers the style if source provided (does NOT overwrite) and enqueues". 但是遍历wp_enqueue_style()的文档时,它说“如果提供了源(不覆盖)并wp_enqueue_style() ,则注册样式”。

So my question is what is the difference in both the techniques. 所以我的问题是两种技术有什么区别。 Is it correct to use the wp_enqueue_style() directly instead of registering and then calling using wp_register_style() and wp_enqueue_style() . 直接使用wp_enqueue_style()而不是注册,然后使用wp_register_style()wp_enqueue_style()调用是否正确? Is there something I'm missing. 有什么我想念的吗?

This means, if you want to register your scripts, but not directly load them in your pages, you can register the files once, and then load them when you need them. 这意味着,如果要注册脚本,但不直接将其加载到页面中,则可以注册一次文件,然后在需要时加载它们。

For example: 例如:

You have a switch statement which loads some functionality, but two of three cases needs a particular javascript file, and one doesn't. 您有一个switch语句,该语句加载了一些功能,但是三种情况中的两种需要一个特定的javascript文件,而另一种则不需要。 You can enqueue the script every time, which costs more resources, or just enqueue the script when you need it: 您可以每次使脚本入队,这会占用更多资源,也可以仅在需要时将其入队:

...
wp_register_script( 'my-handy-javascript', ... );
...
switch( $somevar ) {
    case 'value':
        wp_enqueue_script( 'my-handy-javascript' ); // needs the file
        ...
    break;
    case 'value2':
        wp_enqueue_script( 'my-handy-javascript' ); // needs the file
        ...
    break;
    default:
    case 'value3': // doesn't needs the file
        ...
    break;
}

It is not necessary to register a script and then enqueue them, but it can provide some logic in your code if you register all the scripts you need somewhere in your functions.php instead of everywhere in your code. 不必先注册脚本然后将其排队,但是如果您将所有需要的脚本注册在functions.php中某个位置而不是代码中的任何地方,则可以在代码中提供一些逻辑。

The Codex also tells the following: 食品法典还告知以下内容:

Use the wp_enqueue_scripts action to call this function, or admin_enqueue_scripts to call it on the admin side.

This means that if you want to enqueue your script on the front-end and in the back-end, you can register a script once, and then load it on the front-end with wp_enqueue_script and in the back-end with admin_enqueue_script. 这意味着,如果要在前端和后端排队脚本,可以注册一次脚本,然后使用wp_enqueue_script将其加载到前端,然后使用admin_enqueue_script加载到后端。 This way you won't have the same enqueue recourse twice in one theme, plugin, widget or whatever. 这样,您就不会在一个主题,插件,小部件或其他任何东西上两次获得相同的排队资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM