Skip to content

Use od_finish_template_optimization action to insert video lazy-load script #1922

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: trunk
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@
const LAZY_VIDEO_CLASS_NAME = 'od-lazy-video';

/**
* Whether the lazy-loading script was added to the body.
* Count of lazy-loaded videos on the page.
*
* @since 0.2.0
* @var bool
* @since n.e.x.t
* @var int
*/
protected $added_lazy_script = false;
protected $lazy_loaded_video_count = 0;

/**
* Visits a tag.
Expand Down Expand Up @@ -240,9 +240,20 @@
$processor->add_class( self::LAZY_VIDEO_CLASS_NAME );
}

if ( ! $this->added_lazy_script ) {
$processor->append_body_html( wp_get_inline_script_tag( image_prioritizer_get_video_lazy_load_script(), array( 'type' => 'module' ) ) );
$this->added_lazy_script = true;
++$this->lazy_loaded_video_count;
}

/**
* Inserts lazy-load script if needed.
*
* @since n.e.x.t
*
* @param OD_Template_Optimization_Context $context Template optimization context.
*/
public function insert_lazy_load_script_if_needed( OD_Template_Optimization_Context $context ): void {
if ( $this->lazy_loaded_video_count > 0 ) {
$script = wp_get_inline_script_tag( image_prioritizer_get_video_lazy_load_script(), array( 'type' => 'module' ) );
$context->append_body_html( $script );

Check failure on line 256 in plugins/image-prioritizer/class-image-prioritizer-video-tag-visitor.php

View workflow job for this annotation

GitHub Actions / PHP

Parameter #1 $html of method OD_Template_Optimization_Context::append_body_html() expects non-empty-string, string given.
}
}
}
1 change: 1 addition & 0 deletions plugins/image-prioritizer/helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ function image_prioritizer_register_tag_visitors( OD_Tag_Visitor_Registry $regis

$video_visitor = new Image_Prioritizer_Video_Tag_Visitor();
$registry->register( 'image-prioritizer/video', $video_visitor );
add_action( 'od_finish_template_optimization', array( $video_visitor, 'insert_lazy_load_script_if_needed' ) );
}

/**
Expand Down
Loading