Skip to content

Commit

Permalink
Extract lazy-loading logic into lazy_load_embeds method
Browse files Browse the repository at this point in the history
Signed-off-by: Shyamsundar Gadde <[email protected]>
  • Loading branch information
ShyamGadde committed Dec 20, 2024
1 parent 6778acc commit 7f08b4e
Showing 1 changed file with 29 additions and 15 deletions.
44 changes: 29 additions & 15 deletions plugins/embed-optimizer/class-embed-optimizer-tag-visitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,22 +103,8 @@ public function __invoke( OD_Tag_Visitor_Context $context ): bool {
}

$this->reduce_layout_shifts( $context );

$this->add_preconnect_links( $context );

// Lazy-loading can only be done once there are URL Metrics collected for both mobile and desktop.
if (
$context->url_metric_group_collection->get_first_group()->count() > 0
&&
$context->url_metric_group_collection->get_last_group()->count() > 0
) {
$embed_wrapper_xpath = self::get_embed_wrapper_xpath( $processor->get_xpath() );
$max_intersection_ratio = $context->url_metric_group_collection->get_element_max_intersection_ratio( $embed_wrapper_xpath );
if ( ! ( $max_intersection_ratio > 0.0 ) && embed_optimizer_update_markup( $processor, false ) && ! $this->added_lazy_script ) {
$processor->append_body_html( wp_get_inline_script_tag( embed_optimizer_get_lazy_load_script(), array( 'type' => 'module' ) ) );
$this->added_lazy_script = true;
}
}
$this->lazy_load_embeds( $context );

/*
* At this point the tag is a figure.wp-block-embed, and we can return false because this does not need to be
Expand Down Expand Up @@ -298,4 +284,32 @@ private function add_preconnect_links( OD_Tag_Visitor_Context $context ): void {
}
}
}

/**
* Optimizes an embed based on whether it is displayed in any initial viewport.
*
* @since n.e.x.t
*
* @param OD_Tag_Visitor_Context $context Tag visitor context, with the cursor currently at an embed block.
*/
private function lazy_load_embeds( OD_Tag_Visitor_Context $context ): void {
$processor = $context->processor;

// Lazy-loading can only be done once there are URL Metrics collected for both mobile and desktop.
if (
$context->url_metric_group_collection->get_first_group()->count() === 0
||
$context->url_metric_group_collection->get_last_group()->count() === 0
) {
return;
}

$embed_wrapper_xpath = self::get_embed_wrapper_xpath( $processor->get_xpath() );

$max_intersection_ratio = $context->url_metric_group_collection->get_element_max_intersection_ratio( $embed_wrapper_xpath );
if ( ! ( $max_intersection_ratio > 0.0 ) && embed_optimizer_update_markup( $processor, false ) && ! $this->added_lazy_script ) {
$processor->append_body_html( wp_get_inline_script_tag( embed_optimizer_get_lazy_load_script(), array( 'type' => 'module' ) ) );
$this->added_lazy_script = true;
}
}
}

0 comments on commit 7f08b4e

Please sign in to comment.