Heartbeat Refresh Browser When Page is Updated: The Efficient Solution
Keeping your website content up-to-date and engaging for your visitors is a constant challenge for any web developer or content creator. One common scenario is when you need to ensure that your users are always seeing the latest version of a page, especially when the content has been updated.
In this blog post, we'll explore a robust and efficient solution to this problem using the WordPress Heartbeat API and a bit of JavaScript. By the end, you'll know how to automatically refresh your browser when a page is updated, providing your users with the most current information.
Understanding the Problem
Imagine you have a page on your WordPress website that is frequently updated with new content or information. You want to ensure that your users always see the latest version of this page, without them having to manually refresh the page or clear their browser cache.
The traditional approach would be to implement some form of "cache busting" technique, where you append a unique identifier (e.g., a timestamp or version number) to the page's URL every time the content is updated. This forces the browser to fetch the latest version of the page, rather than serving the cached version.
However, this approach can be cumbersome and may not always be reliable, as it relies on the user actually navigating to the page or triggering a page refresh. Additionally, it can lead to issues with bookmarking or sharing the page, as the URL will change with each update.
The Heartbeat API Solution
Fortunately, WordPress provides a built-in solution for this problem: the Heartbeat API. The Heartbeat API is a mechanism that allows WordPress to regularly communicate with the client-side (browser) and vice versa, without the user having to manually refresh the page.
By leveraging the Heartbeat API, we can create a simple yet effective solution that automatically refreshes the browser when the page content is updated, ensuring that your users always see the most current information.
Implementing the Solution
Let's dive into the step-by-step implementation of this solution:
-
Enqueue the Heartbeat API script:
First, we need to enqueue the Heartbeat API script on the specific page we want to monitor. We can do this by hooking into the wp_enqueue_scripts
action and checking if the current page is the one we're interested in:
function heartbeat_test_enqueue($hook_suffix) {
if (is_page(1105)) {
// Make sure the JS part of the Heartbeat API is loaded.
wp_enqueue_script('heartbeat');
// Output the test JS in admin footer.
add_action('print_footer_scripts', 'heartbeat_update', 20);
// Add filter to receive hook, and specify we need 2 parameters.
add_filter('heartbeat_received', 'dw_receive_heartbeat', 10, 2);
}
}
add_action('wp_enqueue_scripts', 'heartbeat_test_enqueue');
-
Write the modification timestamp to a file:
Next, we'll write the modification timestamp of the page to a text file. We can do this by hooking into the post_updated
action and checking if the current post is the one we're interested in:
function write_timestamp($post_ID, $post_after, $post_before) {
if ($post_ID == 1105) {
$myfile = fopen("URLtoTextFile/tv.txt", "w") or die("Unable to open file!");
$txt = $post_after->post_modified;
fwrite($myfile, $txt);
fclose($myfile);
}
}
add_action('post_updated', 'write_timestamp', 10, 3);
-
Implement the client-side refresh logic:
Finally, we'll use JavaScript to continuously check the modification timestamp in the text file and compare it to the current timestamp. If the timestamps differ, we'll trigger a page refresh:
function heartbeat_update() {
?>
<script>
jQuery(document).ready(function($) {
var current_timestamp;
jQuery.ajax({
url: "/tv.txt",
cache: false,
success: function(data) {
current_timestamp = data;
}
});
// Listen for the custom event "heartbeat-tick" on $(document). This fires once every 15s that the page is open.
jQuery(document).on('heartbeat-tick', function(e, data) {
jQuery.ajax({
url: "/tv.txt",
cache: false,
success: function(data) {
if (data != current_timestamp) {
jQuery('body').fadeOut(1000, function() {
location.reload(true);
});
}
}
});
});
});
</script>
<?php
}
In this JavaScript code, we first retrieve the current modification timestamp from the text file. Then, we listen for the heartbeat-tick
event, which is fired every 15 seconds (the default Heartbeat API interval). When this event is triggered, we check the modification timestamp again and compare it to the stored value. If the timestamps differ, we fade out the page and trigger a full page refresh, ensuring that the user sees the latest version of the content.
-
Adjust the Heartbeat API interval:
By default, the Heartbeat API has a 60-second interval, which may be too long for your needs. You can adjust the interval by adding a filter to the heartbeat_settings
hook:
function m_heartbeat_settings($settings) {
$settings['interval'] = 15; // Only values between 15 and 60 seconds allowed
return $settings;
}
add_filter('heartbeat_settings', 'm_heartbeat_settings');
In this example, we've set the interval to 15 seconds, which means the client-side script will check for updates every 15 seconds.
Benefits of the Heartbeat Refresh Solution
Using the Heartbeat API to automatically refresh the browser when a page is updated offers several benefits:
-
Reliable and Efficient: By continuously monitoring the page's modification timestamp, this solution ensures that users always see the latest version of the content, without the need for manual refreshes or cache clearing.
-
Seamless User Experience: The page refresh is handled transparently, with a smooth fade-out and reload, providing a seamless experience for the user.
-
Scalable and Flexible: The Heartbeat API is a built-in WordPress feature, so this solution can be easily implemented and scaled across multiple pages or even your entire website.
-
Reduced Bounce Rates: By keeping your content up-to-date, you can reduce the likelihood of users leaving your site due to outdated information, ultimately improving your website's engagement and conversion metrics.
-
Improved SEO: Keeping your content fresh and up-to-date can also have a positive impact on your website's search engine optimization (SEO), as search engines tend to favor regularly updated and relevant content.
Conclusion
In this blog post, we've explored a robust and efficient solution to the problem of automatically refreshing the browser when a WordPress page is updated. By leveraging the Heartbeat API and a few lines of PHP and JavaScript code, you can ensure that your users always see the latest version of your content, providing a seamless and engaging experience.
This solution can be a valuable tool in your web development arsenal, helping you keep your website content fresh and up-to-date, while also improving your website's overall performance and user engagement.
If you're interested in further optimizing your website's performance and user experience, be sure to check out Flowpoint.ai, a web analytics platform that uses AI to identify technical, UX/UI, and content-related issues impacting your conversion rates, and provides actionable recommendations to fix them.
Get a Free AI Website Audit
Automatically identify UX and content issues affecting your conversion rates with Flowpoint's comprehensive AI-driven website audit.