Skip to content

Commit

Permalink
Use requestAnimationFrame for FUOC-less resolution (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
bfred-it authored and sindresorhus committed Jun 1, 2017
1 parent ee3b6f8 commit 95af164
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 12 deletions.
16 changes: 4 additions & 12 deletions index.js
Expand Up @@ -8,25 +8,17 @@ module.exports = selector => {
}

const promise = new Promise(resolve => {
const el = document.querySelector(selector);

// Shortcut if the element already exists
if (el) {
resolve(el);
selectorCache.delete(selector);
return;
}

// Interval to keep checking for it to come into the DOM
const awaitElement = setInterval(() => {
(function check() {
const el = document.querySelector(selector);

if (el) {
resolve(el);
clearInterval(awaitElement);
selectorCache.delete(selector);
} else {
requestAnimationFrame(check);
}
}, 50);
})();
});

selectorCache.set(selector, promise);
Expand Down
1 change: 1 addition & 0 deletions test.js
Expand Up @@ -5,6 +5,7 @@ import m from './';

global.document = jsdom.jsdom();
global.window = document.defaultView;
global.requestAnimationFrame = fn => setTimeout(fn, 16);

test('check if element ready', async t => {
const elCheck = m('#unicorn');
Expand Down

0 comments on commit 95af164

Please sign in to comment.