From 1a70841e5fceb2db0201bec14ec3f659de9e0489 Mon Sep 17 00:00:00 2001 From: kagg-design Date: Wed, 4 Dec 2024 00:55:20 +0200 Subject: [PATCH] Add optimization of Monster Insights. --- composer.json | 10 ++--- src/php/DelayedScript.php | 3 +- src/php/Main.php | 1 + src/php/MonsterInsights.php | 81 +++++++++++++++++++++++++++++++++++++ 4 files changed, 89 insertions(+), 6 deletions(-) create mode 100644 src/php/MonsterInsights.php diff --git a/composer.json b/composer.json index 60c0236..7ab9b22 100644 --- a/composer.json +++ b/composer.json @@ -32,19 +32,19 @@ "dealerdirect/phpcodesniffer-composer-installer": true }, "platform": { - "php": "7.0" + "php": "7.2" } }, "require": { "ext-json": "*", - "tedivm/jshrink": "^v1.6.8" + "tedivm/jshrink": "^v1.7.0" }, "require-dev": { "roave/security-advisories": "dev-latest", - "squizlabs/php_codesniffer": "^3.7.2", + "squizlabs/php_codesniffer": "^3.11.1", "phpcompatibility/php-compatibility": "^9.3.5", - "phpcompatibility/phpcompatibility-wp": "^2.1.3", - "wp-coding-standards/wpcs": "^3.0.0" + "phpcompatibility/phpcompatibility-wp": "^2.1.5", + "wp-coding-standards/wpcs": "^3.1.0" }, "autoload": { "psr-4": { diff --git a/src/php/DelayedScript.php b/src/php/DelayedScript.php index 6205932..9fdc66e 100644 --- a/src/php/DelayedScript.php +++ b/src/php/DelayedScript.php @@ -182,6 +182,7 @@ public static function launch_stored_scripts(): void { * @noinspection JSUnusedLocalSymbols */ private static function get_js( array $args, bool $async = true ): string { + unset( $args['async'] ); $async_string = $async ? 'true' : 'false'; $js = << $arg ) { if ( 'data' === $key ) { foreach ( $arg as $data_key => $data_arg ) { - $js .= "\t\t\ts.dataset.$data_key = '$data_arg';\n"; + $js .= "\t\t\ts.setAttribute( 'data-' + '$data_key', '$data_arg' );\n"; } continue; } diff --git a/src/php/Main.php b/src/php/Main.php index d730f49..0364c8b 100644 --- a/src/php/Main.php +++ b/src/php/Main.php @@ -107,6 +107,7 @@ public function init(): void { new FBShareLikeButton(); new StatCounter(); new Clutch(); + new MonsterInsights(); } /** diff --git a/src/php/MonsterInsights.php b/src/php/MonsterInsights.php new file mode 100644 index 0000000..8ed4210 --- /dev/null +++ b/src/php/MonsterInsights.php @@ -0,0 +1,81 @@ +#', $g_tag, $matches ) ) { + $script_tag = $matches[0]; + + preg_match( '##', $script_tag, $matches ); + + $script_args = $matches[1] ?? ''; + + preg_match_all( '#([\w|-]+)=["\']([^"\']+)["\']|([\w|-]+)#', $script_args, $matches ); + + $keys = array_filter( $matches[1] ) + array_filter( $matches[3] ); + $values = $matches[2]; + $args = array_combine( $keys, $values ); + $data = []; + + foreach ( $args as $key => $value ) { + if ( 0 === strpos( $key, 'data-' ) ) { + $data[ str_replace( 'data-', '', $key ) ] = $value; + unset( $args[ $key ] ); + } + } + + $args['data'] = $data; + + $g_tag = str_replace( $script_tag, '', $g_tag ); + + DelayedScript::launch( $args ); + } + + DelayedScript::launch_html( $g_tag ); + } +}