Skip to content

Preload Script

Web Lifter edited this page Jan 22, 2025 · 5 revisions

Dynamic Prefetching and Caching Script

Code File scripts/preload.js

Overview

This script is designed to enhance website performance by:

  • Preloading and caching assets dynamically to reduce perceived load times.
  • Leveraging browser-side sessionStorage for short-term caching during a user's session.
  • Complementing CDN services like Cloudflare by reducing repeated origin server requests.

Features

1. Hover-Based Prefetching

  • Prefetches assets (HTML, CSS, and JS) when the user hovers over a link.
  • Uses a whitelist to control which pages are preloaded.
  • Reduces load time for anticipated user interactions.

2. Click-Based Caching

  • Caches the HTML content of pages on click events.
  • Stores the content in sessionStorage for the duration of the session.

3. Cache Expiration Management

  • Automatically removes cached data that exceeds the defined expiration time (24 hours by default).
  • Runs cleanup operations every hour to maintain efficient storage usage.

4. Enhanced Compatibility

  • Implements feature detection to ensure compatibility with modern browsers.
  • Gracefully degrades functionality in unsupported environments.

5. Analytics Integration

  • Logs prefetching, caching, and cache cleanup actions to the console for tracking and monitoring.

6. Customisable Cache Logic

  • Allows dynamic addition of URLs to the whitelist at runtime for flexible control over prefetching behavior.

Script Workflow

Prefetching

  1. The script listens for mouseover events on links.
  2. Checks if the hovered link is:
    • Whitelisted for prefetching.
    • Not already cached in sessionStorage.
  3. Fetches the page's content and parses it to identify CSS and JS assets.
  4. Preloads these assets using <link> elements with the preload attribute.

Caching

  1. The script listens for click events on links.
  2. Fetches the clicked page’s content using the fetch API.
  3. Stores the HTML content and a timestamp in sessionStorage for future use.

Cache Cleanup

  1. Runs every hour using setInterval.
  2. Iterates through sessionStorage and removes expired entries based on a timestamp comparison.

Integration with Cloudflare CDN

How it Works:

  • Prefetch requests made by the script are routed through Cloudflare.
  • If the requested resource is cached at Cloudflare’s edge server, the response is served instantly.
  • If not, Cloudflare fetches the resource from the origin server and caches it for future use.

Benefits:

  • Faster Initial Loads: Cloudflare serves cached responses quickly.
  • Reduced Origin Load: The script reduces repeated fetch requests to the origin server by utilising browser-side caching.

Recommendations:

  • Configure Cloudflare with proper cache headers (Cache-Control, ETag, etc.) to align with the script’s caching behavior.
  • Automate cache purging in Cloudflare when origin content is updated to avoid serving stale data.

Configuration

Constants

  • CACHE_EXPIRATION_TIME: Sets the lifetime of cached entries in milliseconds. Default is 24 hours.
  • PREFETCH_WHITELIST: An array of URL paths eligible for prefetching. Initially empty but can be populated dynamically.

Dynamic Whitelist Management

Use the addToWhitelist() function to dynamically add URLs:

addToWhitelist(['/example-page', '/another-page']);

## Browser Requirements

### Supported Browsers

The script requires modern browsers that support:

- The fetch API for making asynchronous HTTP requests.
- The DOMParser interface for parsing and manipulating HTML content.

## Feature Detection

The script includes feature detection to check for browser compatibility. If a browser lacks the required features, the script will:

- Skip advanced functionality.
- Log a warning in the console:

```arduino
"Your browser does not support all required features for optimal performance."

Graceful Degradation

Users on unsupported browsers will still be able to navigate the website normally. Performance enhancements (prefetching, caching, etc.) will simply not be applied.

Script Integration

Usage

  1. Add the script file to your website.
  2. Configure the whitelist with the most accessed or critical pages.
  3. Monitor performance and adjust the whitelist and cache policies as needed.

Example Integration

Include the script in your project:

<script src="dynamic-prefetch.js"></script>
<script>
    // Dynamically add pages to the whitelist
    addToWhitelist(['/home', '/about-us', '/contact-us']);
</script>

Example Integration in WordPress

To implement this script on a WordPress website, follow the steps below:

Step 1: Add the Script to Your Theme

Place the dynamic-prefetch.js script file into your WordPress theme's directory, preferably in a folder like assets/js to keep your files organised.

Step 2: Enqueue the Script in WordPress

Use the WordPress wp_enqueue_script function to include the script in your theme or child theme. Add the following code to your theme's functions.php file:

function enqueue_dynamic_prefetch_script() {
    // Register the script
    wp_register_script(
        'dynamic-prefetch', // Handle for the script
        get_template_directory_uri() . '/assets/js/dynamic-prefetch.js', // Path to the script
        array(), // Dependencies (none in this case)
        '1.0.0', // Version
        true // Load in the footer
    );

    // Localize the script to pass dynamic data (optional)
    wp_localize_script(
        'dynamic-prefetch',
        'PrefetchData',
        array(
            'whitelist' => array(
                '/home',
                '/about-us',
                '/contact-us'
            ),
        )
    );

    // Enqueue the script
    wp_enqueue_script('dynamic-prefetch');
}
add_action('wp_enqueue_scripts', 'enqueue_dynamic_prefetch_script');

Step 3: Modify the Script for WordPress

If you'd like to use dynamic data for the whitelist (e.g., fetching URLs from WordPress menus), you can modify the script to read the data passed via wp_localize_script.

In your dynamic-prefetch.js file, modify the whitelist integration as follows:

// Check if PrefetchData and whitelist are available
if (typeof PrefetchData !== 'undefined' && Array.isArray(PrefetchData.whitelist)) {
    // Add URLs from localized data to the whitelist
    addToWhitelist(PrefetchData.whitelist);
}

Step 4: Use in WordPress Pages

The script will now automatically apply to any pages served by your WordPress site. To ensure it works as expected:

  1. Confirm that URLs in the whitelist are relative paths (e.g., /about-us, /contact-us) as WordPress generates such paths for links.
  2. Test the script in various scenarios to ensure compatibility.

Advanced Integration

Dynamic Whitelist Based on Menus

If your site has a dynamic menu managed by WordPress, you can fetch menu items and use them to populate the whitelist. Add the following function to functions.php:

function get_menu_urls_for_prefetch($menu_name) {
    $menu_items = wp_get_nav_menu_items($menu_name);
    $urls = array();

    if ($menu_items) {
        foreach ($menu_items as $item) {
            $urls[] = str_replace(home_url(), '', $item->url); // Convert absolute URL to relative path
        }
    }

    return $urls;
}

function enqueue_dynamic_prefetch_with_menu() {
    // Fetch menu URLs dynamically
    $menu_urls = get_menu_urls_for_prefetch('main-menu'); // Replace 'main-menu' with your menu slug

    wp_register_script(
        'dynamic-prefetch',
        get_template_directory_uri() . '/assets/js/dynamic-prefetch.js',
        array(),
        '1.0.0',
        true
    );

    // Pass menu URLs to the script
    wp_localize_script(
        'dynamic-prefetch',
        'PrefetchData',
        array(
            'whitelist' => $menu_urls,
        )
    );

    wp_enqueue_script('dynamic-prefetch');
}
add_action('wp_enqueue_scripts', 'enqueue_dynamic_prefetch_with_menu');

Optimisation Tips

  • Combine this script with a CDN like Cloudflare for global performance improvements.
  • Use analytics tools to identify high-traffic pages for prefetch prioritisation.

Logging and Debugging

Logs

  • Prefetch Logs: Logs URLs of successfully prefetched pages and assets.
  • Cache Logs: Logs URLs of pages stored or removed from the cache.
  • Error Logs: Captures errors during fetch, parsing, or asset preloading.

Sample Logs

Preloaded: /about-us
Stored in cache: /about-us
Removed expired cache: /contact-us

Development and Contribution

Planned Enhancements

  • Integration with Google Analytics for prefetch and cache tracking.
  • Improved UI feedback for preloading (e.g., progress indicators).
  • Support for offline browsing using Service Workers.