kunoichi/assets-lazy-loader

WordPress主题的懒加载器。

1.2.0 2024-02-26 06:53 UTC

This package is auto-updated.

Last update: 2024-09-26 09:34:56 UTC


README

WordPress主题的懒加载器。

安装

使用composer。

composer require kunoichi/assets-lazy-loader

用法

在你的 functions.php 中逐个启用每个服务。

// in your functions.php
require __DIR__ . '/vendor/autoload.php';

ImageLazyLoader

过滤HTML中的所有 img 标签,并添加 loading="lazy" 属性。如果 img 标签已经具有 loading 属性,则不会再添加更多属性。

// Enable image lazy loader.
Kunoichi\AssetsLazyLoader\ImageLazyLoader::enable();
// If you want exclude some image(e.g. Featured image)
// a filter hook is available.
add_filter( 'assets_lazy_loader_image', function( $should, $tag ) {
	return false !== strpos( $tag,  'size-post-thumbnail' );
}, 10, 2 );

延迟脚本

defer 属性添加到使用 wp_enqueue_script 队列的JavaScript。

Kunoichi\AssetsLazyLoader\ScriptsDefer::enable( [
	'exclude'  => ['jquery-core'], // Only jQuery is not deferred.
	'in_login' => true, // Add defer on login screen. Default false.
	'in_admin' => true, // Same as above.
] );

一些JavaScript通过 wp_add_inline_script 包含以下脚本。这可能导致关键错误。ScriptDefer 跳过带有 after 部分的已排队脚本,但出于更安全起见,请考虑使用允许列表方法。

Kunoichi\AssetsLazyLoader\ScriptsDefer::enable( [
	// Defer scripts only which you know they are safe with defer attribute.
	'exclude'  => [ 'your-js', 'jquery' ], 
] );

CSS预加载

rel="preload" 添加到 link 标签和回退脚本。

Kunoichi\AssetsLazyLoader\StyleLoader::enable( [
	'exclude'  => StyleLoader::admin_critical( ['twentytwenty-style'] ), // Exclude default style and login/admin screen.
	'in_login' => true,
	'in_admin' => true,
] )

CSS预加载会在几秒钟内导致非样式HTML。为了避免通过重新渲染而导致的屏幕缩小,请从预加载中排除关键CSS文件。在许多情况下,这是主题的主样式表。

StyleLoader::admin_critical 对排除管理和登录屏幕中的关键CSS很有帮助。

jQuery增强

WordPress捆绑的默认jQuery有一些问题。

  • 版本过旧(1.12.4)。
  • 随jQuery migrate提供,这对合理的插件和主题来说是不必要的。
  • head 标签中排入队列。

您可以分配其他版本的jQuery并删除 jquery-migrate

JqueryOptimizer::enable( [
	'footer'  => true, // Move jQuery to footer.
	'src'     => 'https://code.jqueryjs.cn/jquery-3.5.1.slim.js', // Slim version from https://code.jqueryjs.cn/
	'version' => '3.5.1', // Specify collect version.
] );

致谢

许可证

GPL 3.0或更高版本。