wp_register_style() 和 wp_enqueue_style 之间的区别

use*_*263 7 php wordpress

我是 WordPress 开发新手。在浏览一些示例代码时wp_register_style(),我遇到了用于注册样式表及其位置的方法,稍后可以使用wp_enqueue_style().

但是浏览 的文档wp_enqueue_style(),它说“如果提供源,则注册样式(不覆盖)并排队”。

所以我的问题是这两种技术有什么区别。直接使用wp_enqueue_style()而不是注册然后使用wp_register_style()和调用是否正确wp_enqueue_style()。我有什么遗漏的吗?

use*_*263 12

这意味着,如果您想注册脚本,但不直接将它们加载到页面中,您可以注册一次文件,然后在需要时加载它们。

例如:

您有一个加载某些功能的 switch 语句,但三种情况中有两种需要特定的 javascript 文件,而另一种则不需要。您可以每次都将脚本入队,这会消耗更多资源,或者只在需要时将脚本入队:

...
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;
}
Run Code Online (Sandbox Code Playgroud)

没有必要注册脚本然后将它们排入队列,但如果您将所需的所有脚本注册在functions.php中的某个位置而不是代码中的任何地方,那么它可以在代码中提供一些逻辑。

食品法典还规定了以下内容:

Use the wp_enqueue_scripts action to call this function, or admin_enqueue_scripts to call it on the admin side.
Run Code Online (Sandbox Code Playgroud)

这意味着,如果您想在前端和后端将脚本排队,您可以注册一个脚本一次,然后使用 wp_enqueue_script 将其加载到前端,并使用 admin_enqueue_script 将其加载到后端。这样,您就不会在一个主题、插件、小部件或其他任何内容中两次拥有相同的队列资源。