Skip to content

Commit

Permalink
lazy load script loader
Browse files Browse the repository at this point in the history
  • Loading branch information
dannyvankooten committed Jan 23, 2025
1 parent ccc1f5f commit d48c95d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 31 deletions.
2 changes: 1 addition & 1 deletion autoload.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@
'KokoAnalytics\\Notice_Pro' => '/src/class-notice-pro.php',
'KokoAnalytics\\Pageview_Aggregator' => '/src/class-pageview-aggregator.php',
'KokoAnalytics\\Rest' => '/src/class-rest.php',
'KokoAnalytics\\Script_Loader' => '/src/class-script-loader.php',
'KokoAnalytics\\Stats' => '/src/class-stats.php',
'KokoAnalytics\\Shortcode_Most_Viewed_Posts' => '/src/class-shortcode-most-viewed-posts.php',
'KokoAnalytics\\Shortcode_Site_Counter' => '/src/class-shortcode-site-counter.php',
'KokoAnalytics\\Stats' => '/src/class-stats.php',
'KokoAnalytics\\Widget_Most_Viewed_Posts' => '/src/class-widget-most-viewed-posts.php',
];

if (isset($classmap[$class])) {
Expand Down
19 changes: 11 additions & 8 deletions koko-analytics.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,15 @@
// wp-admin only
new Admin();
new Dashboard_Widget();
} else {
// frontend only
require __DIR__ . '/src/class-script-loader.php';
new Script_Loader();
add_action('admin_bar_menu', 'KokoAnalytics\admin_bar_menu', 40, 1);
$times[] = ['Script_Loader', microtime(true)];
}

// script loader
add_action('wp_enqueue_scripts', [Script_Loader::class, 'maybe_enqueue_script'], 10, 0);
add_action('amp_print_analytics', [Script_Loader::class, 'print_amp_analytics_tag'], 10, 0);
add_action('admin_bar_menu', 'KokoAnalytics\admin_bar_menu', 40, 1);
$times[] = ['Script_Loader', microtime(true)];

// query loop block
require __DIR__ . '/src/class-query-loop-block.php';
new QueryLoopBlock();
$times[] = ['QueryLoopBlock', microtime(true)];
Expand All @@ -87,6 +88,7 @@
add_action('rest_api_init', [Rest::class, 'register_routes'], 10, 0);
$times[] = ['Rest', microtime(true)];

// pruner
require __DIR__ . '/src/class-pruner.php';
new Pruner();
$times[] = ['Pruner', microtime(true)];
Expand All @@ -96,8 +98,6 @@
$times[] = ['Command', microtime(true)];
}



// register shortcodes
add_shortcode('koko_analytics_most_viewed_posts', [Shortcode_Most_Viewed_Posts::class, 'content']);
$times[] = ['Shortcode_Most_Viewed_Posts', microtime(true)];
Expand Down Expand Up @@ -136,5 +136,8 @@
// for ($i = count($times) - 1; $i > 0; $i--) {
// $times[$i][1] = $times[$i][1] - $times[$i-1][1];
// }
// usort($times, function ($a, $b) {
// return $a[1] === $b[1] ? 0 : ($a[1] > $b[1] ? -1 : 1);
// });

// dump($times);
38 changes: 16 additions & 22 deletions src/class-script-loader.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,10 @@

class Script_Loader
{
public function __construct()
{
add_action('wp_enqueue_scripts', [$this, 'maybe_enqueue_script'], 10, 0);
add_action('amp_print_analytics', [$this, 'print_amp_analytics_tag'], 10, 0);
}

/**
* @param bool $echo Whether to use the default WP script enqueue method or print the script tag directly
*/
public function maybe_enqueue_script(bool $echo = false)
public static function maybe_enqueue_script(bool $echo = false)
{
$load_script = apply_filters('koko_analytics_load_tracking_script', true);
if (! $load_script) {
Expand All @@ -33,20 +27,20 @@ public function maybe_enqueue_script(bool $echo = false)
}

// TODO: Handle "term" requests so we track both terms and post types.
add_filter('script_loader_tag', [ $this, 'add_async_attribute' ], 20, 2);
add_filter('script_loader_tag', [ Script_Loader::class , 'add_async_attribute' ], 20, 2);

if (false === $echo) {
// Print configuration object early on in the HTML so scripts can modify it
if (did_action('wp_head')) {
$this->print_js_object();
self::print_js_object();
} else {
add_action('wp_head', [ $this, 'print_js_object' ], 1, 0);
add_action('wp_head', [ Script_Loader::class , 'print_js_object' ], 1, 0);
}

// Enqueue the actual tracking script (in footer, if possible)
wp_enqueue_script('koko-analytics', plugins_url('assets/dist/js/script.js', KOKO_ANALYTICS_PLUGIN_FILE), [], KOKO_ANALYTICS_VERSION, true);
} else {
$this->print_js_object();
self::print_js_object();
echo '<script defer src="', plugins_url('assets/dist/js/script.js?ver=' . KOKO_ANALYTICS_VERSION, KOKO_ANALYTICS_PLUGIN_FILE), '"></script>';
}
}
Expand All @@ -57,7 +51,7 @@ public function maybe_enqueue_script(bool $echo = false)
*
* @return int
*/
private function get_post_id(): int
private static function get_post_id(): int
{
if (is_singular()) {
return get_queried_object_id();
Expand All @@ -70,7 +64,7 @@ private function get_post_id(): int
return -1;
}

private function get_tracker_url(): string
private static function get_tracker_url(): string
{
if (defined('KOKO_ANALYTICS_CUSTOM_ENDPOINT') && KOKO_ANALYTICS_CUSTOM_ENDPOINT) {
return site_url(KOKO_ANALYTICS_CUSTOM_ENDPOINT);
Expand All @@ -81,37 +75,37 @@ private function get_tracker_url(): string
return using_custom_endpoint() ? site_url('/koko-analytics-collect.php') : admin_url('admin-ajax.php?action=koko_analytics_collect');
}

private function get_cookie_path(): string
private static function get_cookie_path(): string
{
$home_url = home_url();
return parse_url($home_url, PHP_URL_PATH) ?? '/';
}

public function print_js_object()
public static function print_js_object()
{
$settings = get_settings();
$script_config = [
// the URL of the tracking endpoint
'url' => $this->get_tracker_url(),
'url' => self::get_tracker_url(),
'site_url' => get_home_url(),

// ID of the current post (or -1 in case of non-singular type)
'post_id' => $this->get_post_id(),
'post_id' => self::get_post_id(),

// wether to set a cookie
'use_cookie' => (int) $settings['use_cookie'],

// path to store the cookie in (will be subdirectory if website root is in subdirectory)
'cookie_path' => $this->get_cookie_path(),
'cookie_path' => self::get_cookie_path(),
];
echo '<script>window.koko_analytics = ', json_encode($script_config), ';</script>';
}

public function print_amp_analytics_tag()
public static function print_amp_analytics_tag()
{
$settings = get_settings();
$post_id = $this->get_post_id();
$tracker_url = $this->get_tracker_url();
$post_id = self::get_post_id();
$tracker_url = self::get_tracker_url();
$posts_viewed = isset($_COOKIE['_koko_analytics_pages_viewed']) ? explode(',', $_COOKIE['_koko_analytics_pages_viewed']) : [];
$data = [
'sc' => $settings['use_cookie'], // inform tracker endpoint to set cookie server-side
Expand Down Expand Up @@ -139,7 +133,7 @@ public function print_amp_analytics_tag()
* @param string $tag
* @param string $handle
*/
public function add_async_attribute($tag, $handle)
public static function add_async_attribute($tag, $handle)
{
if ($handle !== 'koko-analytics' || strpos($tag, ' defer') !== false) {
return $tag;
Expand Down

0 comments on commit d48c95d

Please sign in to comment.