-
-
Notifications
You must be signed in to change notification settings - Fork 0
Preload Script
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.
- 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.
- Caches the HTML content of pages on click events.
- Stores the content in
sessionStorage
for the duration of the session.
- Automatically removes cached data that exceeds the defined expiration time (24 hours by default).
- Runs cleanup operations every hour to maintain efficient storage usage.
- Implements feature detection to ensure compatibility with modern browsers.
- Gracefully degrades functionality in unsupported environments.
- Logs prefetching, caching, and cache cleanup actions to the console for tracking and monitoring.
- Allows dynamic addition of URLs to the whitelist at runtime for flexible control over prefetching behavior.
- The script listens for
mouseover
events on links. - Checks if the hovered link is:
- Whitelisted for prefetching.
- Not already cached in
sessionStorage
.
- Fetches the page's content and parses it to identify CSS and JS assets.
- Preloads these assets using
<link>
elements with thepreload
attribute.
- The script listens for
click
events on links. - Fetches the clicked page’s content using the
fetch
API. - Stores the HTML content and a timestamp in
sessionStorage
for future use.
- Runs every hour using
setInterval
. - Iterates through
sessionStorage
and removes expired entries based on a timestamp comparison.
- 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.
- 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.
- 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.
-
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.
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."
Users on unsupported browsers will still be able to navigate the website normally. Performance enhancements (prefetching, caching, etc.) will simply not be applied.
- Add the script file to your website.
- Configure the whitelist with the most accessed or critical pages.
- Monitor performance and adjust the whitelist and cache policies as needed.
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>
To implement this script on a WordPress website, follow the steps below:
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.
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');
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);
}
The script will now automatically apply to any pages served by your WordPress site. To ensure it works as expected:
- Confirm that URLs in the whitelist are relative paths (e.g.,
/about-us
,/contact-us
) as WordPress generates such paths for links. - Test the script in various scenarios to ensure compatibility.
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');
- Combine this script with a CDN like Cloudflare for global performance improvements.
- Use analytics tools to identify high-traffic pages for prefetch prioritisation.
- 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.
Preloaded: /about-us
Stored in cache: /about-us
Removed expired cache: /contact-us
- 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.