perf: only observe if window/document/tab is focused

This commit is contained in:
dragonwocky 2021-12-10 14:41:29 +11:00
parent 9b47ede63e
commit d984c8bc36
2 changed files with 20 additions and 19 deletions

File diff suppressed because one or more lines are too long

View File

@ -26,17 +26,18 @@ let _hotkeyListenersActivated = false,
*/ */
export const whenReady = (selectors = []) => { export const whenReady = (selectors = []) => {
return new Promise((res, rej) => { return new Promise((res, rej) => {
function onLoad() { const onLoad = () => {
let isReadyInt; const interval = setInterval(isReady, 100);
isReadyInt = setInterval(isReadyTest, 100); function isReady() {
function isReadyTest() { const ready =
if (selectors.every((selector) => document.querySelector(selector))) { document.hasFocus() &&
clearInterval(isReadyInt); selectors.every((selector) => document.querySelector(selector));
res(true); if (!ready) return;
} clearInterval(interval);
res(true);
} }
isReadyTest(); isReady();
} };
if (document.readyState !== 'complete') { if (document.readyState !== 'complete') {
document.addEventListener('readystatechange', (event) => { document.addEventListener('readystatechange', (event) => {
if (document.readyState === 'complete') onLoad(); if (document.readyState === 'complete') onLoad();
@ -169,7 +170,7 @@ export const readFromClipboard = () => {
const triggerHotkeyListener = (event, hotkey) => { const triggerHotkeyListener = (event, hotkey) => {
const inInput = document.activeElement.nodeName === 'INPUT' && !hotkey.listenInInput; const inInput = document.activeElement.nodeName === 'INPUT' && !hotkey.listenInInput;
if (inInput) return; if (inInput || !document.hasFocus()) return;
const pressed = hotkey.keys.every((key) => { const pressed = hotkey.keys.every((key) => {
key = key.toLowerCase(); key = key.toLowerCase();
const modifiers = { const modifiers = {
@ -261,7 +262,7 @@ export const addDocumentObserver = (callback, selectors = []) => {
} }
}; };
_documentObserver = new MutationObserver((list, observer) => { _documentObserver = new MutationObserver((list, observer) => {
if (!_documentObserverEvents.length) if (!_documentObserverEvents.length && document.hasFocus())
requestIdleCallback(() => handle(_documentObserverEvents)); requestIdleCallback(() => handle(_documentObserverEvents));
_documentObserverEvents.push(...list); _documentObserverEvents.push(...list);
}); });