From 5cd84c56b7001c7d098cbe378627be2f23008d28 Mon Sep 17 00:00:00 2001 From: Gerben Date: Sun, 27 May 2018 23:15:22 +0200 Subject: [PATCH] Try use a mutation observer Instead of every scrolling action, which made scrolling slow on some pages. This will probably be slow on pages with many DOM changes, so not ideal either.. --- src/content_script.js | 44 ++++++++++++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 9 deletions(-) diff --git a/src/content_script.js b/src/content_script.js index d184bec..4975ef1 100644 --- a/src/content_script.js +++ b/src/content_script.js @@ -50,27 +50,53 @@ function hideBanners() { return revertSteps } -function main() { +async function main() { let revertSteps = [] // XXX We read the location only once, but it may be changed by page scripts. // Fortunately we only need the origin, which should remain the same. const url = window.location.href - async function run() { - const enabled = await isEnabled(url) - if (enabled && window.scrollY > 20) { + function run() { + if (enabled && scrolledDown) { // Hide everything that looks annoying. Remember the steps to revert this. revertSteps = hideBanners().concat(revertSteps) - } else if (!enabled || window.scrollY <= 0) { + } else { // Unhide everything we have hidden. - revertSteps.forEach(step => step()) - revertSteps = [] + if (revertSteps.length > 0) { + revertSteps.forEach(step => step()) + revertSteps = [] + } } } - window.addEventListener('scroll', throttle(run, 300)) - onEnabledChange(url, run) + // Run whenever the extension is enabled/disabled for this domain. + let enabled = await isEnabled(url) + onEnabledChange(url, newValue => { enabled = newValue; run() }) + + // Run whenever crossing the scroll threshold. + let scrolledDown = window.scrollY > 20 + window.addEventListener('scroll', () => { + // We add a hysteresis of 20px. + if (window.scrollY > 20 && !scrolledDown) { + scrolledDown = true + run() + } else if (window.scrollY <= 0 && scrolledDown) { + scrolledDown = false + run() + } + }) + + // Run on any page mutation, but at most once per second. + const observer = new MutationObserver(throttle(() => run(), 1000)) + observer.observe(document, { + subtree: true, + childList: true, + attributes: true, + }) + + // Run once now. + run() } main()