Backward Compatible WP Heartbeat API Usage

I wanted to utilize the WP 3.6 heartbeat API in an app I’m working on. I also wanted to include this feature before WordPress 3.6 officially shipped, so that meant it had to be compatible with WordPress 3.5.x as well.

Turns out, it’s really easy. The heartbeat API looks excellent.


<?php
// enqueue the script,
// this fails gracefully if no 'heartbeat' script is registered
wp_enqueue_script('heartbeat');


(function($) {
// watch for heartbeat event,
// no event will happen if the script isn't included
$(document).on('heartbeat-connection-lost', function() {
// do what you need to do here
$('body').addClass('connection-lost')
}).on('heartbeat-connection-restored', function() {
// do what you need to do here
$('body').removeClass('connection-lost')
});
})(jQuery);