diff --git a/module-i18n.php b/module-i18n.php index 5270c77bf..6a7650784 100644 --- a/module-i18n.php +++ b/module-i18n.php @@ -9,6 +9,8 @@ _x( 'Creates WebP versions for new JPEG image uploads if supported by the server.', 'module description', 'performance-lab' ), _x( 'Enqueued Assets Health Check', 'module name', 'performance-lab' ), _x( 'Adds a CSS and JS resource check in Site Health status.', 'module description', 'performance-lab' ), + _x( 'oEmbed Optimizer', 'module name', 'performance-lab' ), + _x( 'Optimize oEmbed loading with improved lazy loading.', 'module description', 'performance-lab' ), _x( 'Autoloaded Options Health Check', 'module name', 'performance-lab' ), _x( 'Adds a check for autoloaded options in Site Health status.', 'module description', 'performance-lab' ), ); diff --git a/modules/js-and-css/optimize-oembeds/hooks.php b/modules/js-and-css/optimize-oembeds/hooks.php new file mode 100644 index 000000000..f419c4601 --- /dev/null +++ b/modules/js-and-css/optimize-oembeds/hooks.php @@ -0,0 +1,115 @@ +next_tag() ) { + if ( 'IFRAME' === $p->get_tag() ) { + $loading_value = $p->get_attribute( 'loading' ); + if ( empty( $loading_value ) ) { + ++$iframe_count; + $p->set_bookmark( 'iframe' ); + } + } elseif ( 'SCRIPT' === $p->get_tag() ) { + if ( ! $p->get_attribute( 'src' ) ) { + $has_inline_script = true; + } else { + ++$script_count; + $p->set_bookmark( 'script' ); + } + } + } + // If there was only one non-inline script, make it lazy. + if ( 1 === $script_count && ! $has_inline_script ) { + add_action( 'wp_footer', 'perflab_optimize_oembed_lazy_load_scripts' ); + $p->seek( 'script' ); + $p->set_attribute( 'data-lazy-embed-src', $p->get_attribute( 'src' ) ); + $p->remove_attribute( 'src' ); + } + // If there was only one iframe, make it lazy. + if ( 1 === $iframe_count ) { + $p->seek( 'iframe' ); + $p->set_attribute( 'loading', 'lazy' ); + } + return $p->get_updated_html(); +} +add_filter( 'embed_oembed_html', 'perflab_optimize_oembed_html' ); + +/** + * Add a script to the footer if there are lazy loaded embeds. + * Load the embed's scripts when they approach the viewport using an IntersectionObserver. + * + * @since n.e.x.t + */ +function perflab_optimize_oembed_lazy_load_scripts() { + ?> + +