Skip to content
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

Closes #6432: Bail out from beacon conditions #6555

76 changes: 53 additions & 23 deletions assets/js/lcp-beacon.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ function isIntersecting(rect) {
}

function LCPCandidates(count) {
const potentialCandidates = document.querySelectorAll(
"img, video, p, main, div"
);
const topCandidates = [];
const potentialCandidates = document.querySelectorAll(
"img, video, p, main, div"
); // Adjust selectors as needed
const topCandidates = [];

potentialCandidates.forEach((element) => {
const rect = element.getBoundingClientRect();
potentialCandidates.forEach((element) => {
const rect = element.getBoundingClientRect();
if (
rect.width > 0 &&
rect.height > 0 &&
Expand All @@ -22,23 +22,25 @@ function LCPCandidates(count) {
const visibleHeight = Math.min(rect.height, (window.innerHeight || document.documentElement.clientHeight) - rect.top);
const area = visibleWidth * visibleHeight;
const imageURL = getImageUrlFromElement(element);
if (imageURL !== null) {
for (let i = 0; i < topCandidates.length; i++) {
if (area > topCandidates[i].area) {
topCandidates.splice(i, 0, { element, area, imageURL });
topCandidates.length = Math.min(
count,
topCandidates.length
);
break;
}
}
if (topCandidates.length < count) {
topCandidates.push({ element, area, imageURL });
}
}
}
});
if (imageURL !== null) {
// Insert element into topCandidates in descending order of area
for (let i = 0; i < topCandidates.length; i++) {
if (area > topCandidates[i].area) {
topCandidates.splice(i, 0, { element, area, imageURL });
topCandidates.length = Math.min(
count,
topCandidates.length
); // Keep only specified number of elements
break;
}
}
// If topCandidates is not full, append
if (topCandidates.length < count) {
topCandidates.push({ element, area, imageURL });
}
}
}
});

return topCandidates.map((candidate) => ({
element: candidate.element,
Expand Down Expand Up @@ -71,6 +73,34 @@ function getImageUrlFromElement(element) {
let performance_images = [];

async function main() {
// AJAX call to check if there are any records for the current URL
let data_check = new FormData();
data_check.append('action', 'rocket_check_lcp');
data_check.append('rocket_lcp_nonce', rocket_lcp_data.nonce);
data_check.append('url', rocket_lcp_data.url);
data_check.append('is_mobile', rocket_lcp_data.is_mobile);

const response = await fetch(rocket_lcp_data.ajax_url, {
method: "POST",
credentials: 'same-origin',
body: data_check
});

if ( true === lcp_data.success ) {
console.log('Bailing out because data is already available');
return;
}

// Check screen size
const screenWidth = window.innerWidth || document.documentElement.clientWidth;
const screenHeight = window.innerHeight || document.documentElement.clientHeight;
if ( ( rocket_lcp_data.is_mobile && ( screenWidth > rocket_lcp_data.width_threshold || screenHeight > rocket_lcp_data.height_threshold ) ) ||
( ! rocket_lcp_data.is_mobile && ( screenWidth < rocket_lcp_data.width_threshold || screenHeight < rocket_lcp_data.height_threshold ) ) )
{
console.log('Bailing out because screen size is not acceptable');
return;
}

// Filter the array based on the condition imageURL is not null
const filteredArray = LCPCandidates(1)
if (filteredArray.length !== 0) {
Expand Down
2 changes: 1 addition & 1 deletion assets/js/lcp-beacon.js.min.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion assets/js/lcp-beacon.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 30 additions & 0 deletions inc/Engine/Media/AboveTheFold/AJAX/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,34 @@ public function add_lcp_data() {

wp_send_json_success( $item );
}

/**
* Checks if there is existing LCP data for the current URL and device type.
*
* This method is called via AJAX. It checks if there is existing LCP data for the current URL and device type.
* If the data exists, it returns a JSON success response with true. If the data does not exist, it returns a JSON success response with false.
* If the context is not allowed, it returns a JSON error response with false.
*
* @return void
*/
public function check_lcp_data() {
check_ajax_referer( 'rocket_lcp', 'rocket_lcp_nonce' );

if ( ! $this->context->is_allowed() ) {
wp_send_json_error( false );
return;
}

$url = isset( $_POST['url'] ) ? untrailingslashit( esc_url_raw( wp_unslash( $_POST['url'] ) ) ) : '';
$is_mobile = isset( $_POST['is_mobile'] ) ? filter_var( wp_unslash( $_POST['is_mobile'] ), FILTER_VALIDATE_BOOLEAN ) : false;

$row = $this->query->get_row( $url, $is_mobile );

if ( ! empty( $row ) ) {
wp_send_json_success( 'data already exists' );
return;
}

wp_send_json_error( 'data does not exist' );
}
}
15 changes: 13 additions & 2 deletions inc/Engine/Media/AboveTheFold/AJAX/Subscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,10 @@ public function __construct( Controller $controller ) {
*/
public static function get_subscribed_events() {
return [
'wp_ajax_rocket_lcp' => 'add_lcp_data',
'wp_ajax_nopriv_rocket_lcp' => 'add_lcp_data',
'wp_ajax_rocket_lcp' => 'add_lcp_data',
'wp_ajax_nopriv_rocket_lcp' => 'add_lcp_data',
'wp_ajax_rocket_check_lcp' => 'check_lcp_data',
'wp_ajax_nopriv_rocket_check_lcp' => 'check_lcp_data',
];
}

Expand All @@ -42,4 +44,13 @@ public static function get_subscribed_events() {
public function add_lcp_data() {
$this->controller->add_lcp_data();
}

/**
* Callback for checking lcp data
*
* @return void
*/
public function check_lcp_data() {
$this->controller->check_lcp_data();
}
}
32 changes: 28 additions & 4 deletions inc/Engine/Media/AboveTheFold/Frontend/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -354,11 +354,35 @@ public function inject_beacon( $html, $url, $is_mobile ): string {
return $html;
}

/**
* Filters the width threshold for the LCP beacon.
*
* @param int $width_threshold The width threshold. Default is 393 for mobile and 1920 for others.
* @param bool $is_mobile True if the current device is mobile, false otherwise.
* @param string $url The current URL.
*
* @return int The filtered width threshold.
*/
$width_threshold = apply_filters( 'rocket_lcp_width_threshold', ( $is_mobile ? 393 : 1920 ), $is_mobile, $url );

/**
* Filters the height threshold for the LCP beacon.
*
* @param int $height_threshold The height threshold. Default is 830 for mobile and 1080 for others.
* @param bool $is_mobile True if the current device is mobile, false otherwise.
* @param string $url The current URL.
*
* @return int The filtered height threshold.
*/
$height_threshold = apply_filters( 'rocket_lcp_height_threshold', ( $is_mobile ? 830 : 1080 ), $is_mobile, $url );

$data = [
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'rocket_lcp' ),
'url' => $url,
'is_mobile' => $is_mobile,
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'rocket_lcp' ),
'url' => $url,
'is_mobile' => $is_mobile,
'width_threshold' => $width_threshold,
'height_threshold' => $height_threshold,
];

$inline_script = '<script>var rocket_lcp_data = ' . wp_json_encode( $data ) . '</script>';
Expand Down
Loading
Loading