wp-feature-notifications
wp-feature-notifications copied to clipboard
Feature: Notification polling on the client
What?
This PR adds notification polling, currently based on the heartbeat API from WordPress.
Why?
This attempts to solve the following issue: https://github.com/WordPress/wp-feature-notifications/issues/306
How?
This PR adds a new Poller class that abstracts how/when/how often the notifications are polled. It makes sense to use the existing Heartbeat API from WordPress since it is reliable. The Heartbeat API is a simple server polling API built into WordPress, allowing near-real-time frontend updates. Heartbeat API Docs
The Poller class hooks into the heartbeat.tick event, which is triggered on a successful heartbeat (in case the user session expired or there is another error, we also skip useless polls to the API).
There is a parameter that is passed to the Poller class named shouldSkipFirstBeat which solves the following edge-case: we load all notifications on page load, but also on some pages, the heartbeat API runs very early on the page load (eg: on post edit/create screen, on post list).
To avoid double, repeated polls to fetch notifications, the first Poller.SKIP_FIRST_INTERVAL milliseconds, any heartbeat tick events are ignored.
The Poller instance is added to the notifications (window.wp.notifications) object, so you can easily do:
window.wp.notifications.poller.stop()- Stop pollingwindow.wp.notifications.poller.start()- Start/resume polling
Testing Instructions
- Visit any page on
wp-admin - Wait for a heartbeat tick event
- Notice the polling request.
- Visit the posts page. Check that only one call is made on page load.
I am open to suggestions and ideas, also if you want to use a setInterval/setTimeout instead of the Heartbeats API, let pe know. I think it is appropriate though.
Closes #306
@filipac my apologies for leaving this unreviewed for so long! Unfortunately things have been on hold a little bit due to team availability and illness, but I'm eager to get things rolling again so will give this a look shortly.
Heartbeat may be turned off as it's got a reputation for slowing sites down, and if you google WP performance hacks, disabling or limiting Heartbeat often comes up.
Plugins that disable or limit Heartbeat (not a comprehensive list): https://perfmatters.io/ https://wordpress.org/plugins/heartbeat-control/ https://wordpress.org/plugins/sg-cachepress/ https://wordpress.org/plugins/litespeed-cache/ or search on WP plugin directory: https://wordpress.org/plugins/search/heartbeat/
Articles: https://perfmatters.io/docs/disable-wordpress-heartbeat-api/ https://www.wpbeginner.com/plugins/how-to-limit-heartbeat-api-in-wordpress/ https://www.hostinger.com/tutorials/wordpress-heartbeat
If we rely on Heartbeat we may first need to check it's enabled, and runs often enough. Maybe add a notification / warning if it's turned off.