refresh.ts 710 B

123456789101112131415161718192021222324252627282930313233
  1. import initClient from '../initializers/initClient';
  2. function addRefresh() {
  3. let pendingReload = false;
  4. initClient({
  5. // @ts-expect-error That's because of the dynamic code loading
  6. id: __HMR_ID,
  7. onUpdate: () => {
  8. // disable reload when tab is hidden
  9. if (document.hidden) {
  10. pendingReload = true;
  11. return;
  12. }
  13. reload();
  14. },
  15. });
  16. // reload
  17. function reload(): void {
  18. pendingReload = false;
  19. window.location.reload();
  20. }
  21. // reload when tab is visible
  22. function reloadWhenTabIsVisible(): void {
  23. !document.hidden && pendingReload && reload();
  24. }
  25. document.addEventListener('visibilitychange', reloadWhenTabIsVisible);
  26. }
  27. addRefresh();