Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit fa03924

Browse files
committed
Prevent detection script injection from breaking import maps
1 parent 747956b commit fa03924

1 file changed

Lines changed: 18 additions & 7 deletions

File tree

plugins/optimization-detective/optimization.php

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
exit; // Exit if accessed directly.
1111
}
1212

13+
const OD_DETECTION_SCRIPT_PLACEHOLDER_COMMENT = '<!--OPTIMIZATION_DETECTIVE_DETECTION_SCRIPT-->';
14+
1315
/**
1416
* Starts output buffering at the end of the 'template_include' filter.
1517
*
@@ -62,6 +64,12 @@ function od_maybe_add_template_output_buffer_filter() {
6264
$callback = perflab_wrap_server_timing( $callback, 'optimization-detective', 'exist' );
6365
}
6466
add_filter( 'od_template_output_buffer', $callback );
67+
add_action(
68+
'wp_print_footer_scripts',
69+
static function () {
70+
echo OD_DETECTION_SCRIPT_PLACEHOLDER_COMMENT; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
71+
}
72+
);
6573
}
6674

6775
/**
@@ -340,13 +348,6 @@ function od_optimize_template_output_buffer( string $buffer ): string {
340348
// Inject any preload links at the end of the HEAD. In the future, WP_HTML_Processor could be used to do this injection.
341349
// However, given the simple replacement here this is not essential.
342350
$head_injection = od_construct_preload_links( $lcp_elements_by_minimum_viewport_widths );
343-
344-
// Inject detection script.
345-
// TODO: When optimizing above, if we find that there is a stored LCP element but it fails to match, it should perhaps set $needs_detection to true and send the request with an override nonce. However, this would require backtracking and adding the data-od-xpath attributes.
346-
if ( $needs_detection ) {
347-
$head_injection .= od_get_detection_script( $slug, $group_collection );
348-
}
349-
350351
if ( $head_injection ) {
351352
$buffer = preg_replace(
352353
'#(?=</HEAD>)#i',
@@ -356,5 +357,15 @@ function od_optimize_template_output_buffer( string $buffer ): string {
356357
);
357358
}
358359

360+
// Inject detection script.
361+
// TODO: When optimizing above, if we find that there is a stored LCP element but it fails to match, it should perhaps set $needs_detection to true and send the request with an override nonce. However, this would require backtracking and adding the data-od-xpath attributes.
362+
if ( $needs_detection ) {
363+
$buffer = str_replace(
364+
OD_DETECTION_SCRIPT_PLACEHOLDER_COMMENT,
365+
od_get_detection_script( $slug, $group_collection ),
366+
$buffer
367+
);
368+
}
369+
359370
return $buffer;
360371
}

0 commit comments

Comments
 (0)