From 44724baa9faaeb9ebfee2fd1211f42a30fb2fff6 Mon Sep 17 00:00:00 2001 From: Mike Crantea Date: Mon, 30 Mar 2020 16:50:06 +0100 Subject: [PATCH] 0.3.3 - Add possibility to report events only on % of traffic --- README.md | 10 ++++++++++ php/Plugin.php | 25 ++++++++++++++++++++++--- site-performance-tracker.php | 2 +- 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ee6592c..30f5de1 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,16 @@ if ( function_exists( 'get_the_performance_mark' ) ) { } ``` +### Limit the number of events sent + +Using the following filter you can send the events for a limited percentage of your traffic, this limits the performance metrics to be sent only for 5% of the traffic: + +```php +add_filter( 'site_performance_tracker_chance', function() { + return 0.05; +} ); +``` + ### Hooks There are the following hooks available to further customize the way the plugin works: diff --git a/php/Plugin.php b/php/Plugin.php index b39de73..a1d95cb 100644 --- a/php/Plugin.php +++ b/php/Plugin.php @@ -20,6 +20,13 @@ class Plugin { */ protected $default_entry_types = array( 'paint', 'navigation', 'mark', 'first-input' ); + /** + * PerformanceObserver default chance of sending performance metrics to analytics. + * + * @var array + */ + protected $default_chance = 1; + /** * Initialize the plugin. */ @@ -87,10 +94,18 @@ public function inject_performance_observer() { */ $entry_types = apply_filters( 'site_performance_tracker_entry_types', $this->default_entry_types ); + /** + * Limits the percentage of traffic chance of sending events to analytics. + * + * @param number $entry_chance Chance - a number between 0 and 1. + */ + $chance = apply_filters( 'site_performance_tracker_chance', $this->default_chance ); + // Options object passed to JS. $options = array( 'categoryName' => $category_name, 'entryTypes' => $entry_types, + 'chance' => $chance, ); ?> @@ -130,9 +145,13 @@ public function inject_performance_observer() { } } } ); - window.sitePerformanceObserver.instance.observe( { - entryTypes: window.sitePerformanceObserver.entryTypes - } ); + var randNumber = Math.random(); + if ( randNumber <= window.sitePerformanceObserver.chance ) { + window.sitePerformanceObserver.instance.observe( { + entryTypes: window.sitePerformanceObserver.entryTypes + } ); + } + }