Everything here assumes a single document and a single user. Both assumptions break eventually, and the resulting failures are interesting because they are the same shape as the original problem, only larger.
There is a version of this that fits in a blog post and a version that fits in a book. The difference is what happens when it fails. If you cannot describe the failure mode, you do not understand the system well enough to ship it.
We used a feature query, a polyfill, and a fallback that shipped the old behaviour. It is unglamorous and it works, and it has survived three major browser releases without incident.