markjaquith / encute
脚本和样式的流畅管理。
v0.8.8
2022-02-17 20:27 UTC
Requires
- php: ^7.4|^8.0
- psr/container: ^1.1
Requires (Dev)
- php: ^7.2|^8.0
- coenjacobs/mozart: dev-master
- friendsofphp/php-cs-fixer: ^3.6
- phpunit/phpunit: ^9.5
- yoast/phpunit-polyfills: ^1.0
README
WordPress 插件,用于流畅管理脚本和样式。
在网站前端管理脚本和样式可能会很复杂。这使得以下操作变得非常简单:
- 将脚本(及其整个关联家族)推入页脚
- 延迟脚本或样式的加载直到页面加载
- 异步加载脚本
- 将脚本标记为
type="module"
- 将脚本标记为
nomodule
- 移除不需要的插件脚本或样式
安装
如果您使用 composer,可以使用 composer require markjaquith/encute
。否则,通过 Git 安装。
使用
将其放在 mu-plugins
插件中
<?php use CWS\Encute\Plugin; use CWS\Encute\Script; use CWS\Encute\Style; add_action(Plugin::class, function (Plugin $encute) { $encute->debug(); // Optional: Adds HTML comments to scripts and styles, making it easier to see the handle. // Move jQuery to footer and defer its loading. Script::get('jquery')->footer()->defer(); // Move 'some-handle' to the footer. Script::get('some-handle')->footer(); // Defer 'wp-embed'. Script::get('wp-embed')->defer(); // Make 'some-module' load as a module. Script::get('some-module')->module(); // Make 'nomodule-fallback' load as nomodule. Script::get('nomodule-fallback')->noModule(); // Move 'admin-bar' styles to the footer and defer their loading. Style::get('admin-bar')->footer()->defer(); // Move 'wp-block-library' styles to the footer. Style::get('wp-block-library')->footer(); // Keep 'contact-form-7' style on contact page only. Style::get('contact-form-7')->keepIf(fn() => is_page('contact')); // Remove 'cruft' script on the about page. Script::get('cruft')->removeIf(fn() => is_page('about')); });
API
初始化
始终在以下包装器中运行代码
add_action(\CWS\Encute\Plugin::class, function (\CWS\Encute\Plugin $encute) { // Your code here. });
如果 Encute 不可用,此包装器将不执行任何操作,并且它将等待 Encute 可用以运行,并将 Encute 的主要类实例传递给您。
流畅性
Script::get()
和 Style::get()
返回一个实例,以及它们的所有方法调用,因此您可以轻松地链式调用。
脚本
static CWS\Encute\Script::get(string $handle): CWS\Encute\Script
— 获取具有该句柄的脚本实例。CWS\Encute\Script::module(): CWS\Encute\Script
— 将脚本作为模块。CWS\Encute\Script::noModule(): CWS\Encute\Script
— 将脚本作为 nomodule。CWS\Encute\Script::footer(): CWS\Encute\Script
— 将脚本发送到页脚(及其整个依赖家族)。CWS\Encute\Script::async(): CWS\Encute\Script
— 使脚本异步。CWS\Encute\Script::defer(): CWS\Encute\Script
— 使脚本延迟。CWS\Encute\Script::remove(): CWS\Encute\Script
— 移除脚本。CWS\Encute\Script::removeIf(callable $callback): CWS\Encute\Script
— 如果回调解析为 true,则移除脚本。CWS\Encute\Script::keepIf(callable $callback): CWS\Encute\Script
— 如果回调解析为 true,则保留脚本(否则移除它)。
样式
static CWS\Encute\Style::get(string $handle): CWS\Encute\Style
— 获取具有该句柄的样式实例。CWS\Encute\Style::footer(): CWS\Encute\Style
— 将样式发送到页脚(及其整个依赖家族)。CWS\Encute\Style::defer(): CWS\Encute\Style
— 延迟样式的加载。CWS\Encute\Style::remove(): CWS\Encute\Style
— 移除样式。CWS\Encute\Style::removeIf(callable $callback): CWS\Encute\Style
— 如果回调解析为 true,则移除样式。CWS\Encute\Style::keepIf(callable $callback): CWS\Encute\Style
— 如果回调解析为 true,则保留样式(否则移除它)。