Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve isVisible for correctness and performance #118

Closed
biancadanforth opened this issue Jul 24, 2019 · 2 comments
Closed

Improve isVisible for correctness and performance #118

biancadanforth opened this issue Jul 24, 2019 · 2 comments
Assignees

Comments

@biancadanforth
Copy link
Collaborator

Related to #91 .

As mentioned in this Price Tracker issue, isVisible overwhelmingly contributes to excessive jank right around page load.

Since Fathom's isVisible method is largely based on Price Tracker's, it suffers from this same problem, and it would be a good idea to have a more performant implementation.

Additionally, the current implementation in Fathom has a bug, so this should be fixed as well.

@biancadanforth biancadanforth self-assigned this Jul 24, 2019
biancadanforth added a commit that referenced this issue Jul 24, 2019
Compared to a baseline profile[1] of Price Tracker's current 'isVisible' implementation (on which Fathom's 'isVisible' method is based), this clickability approach offers a 53% (146 ms) reduction in Fathom-related jank[2] for the same locally hosted sample page.

This is largely due to removing the use of the 'ancestors' Fathom method in 'isVisible'[3], which was performing a lot of redundant layout accesses (and triggering a lot of layout flushes) for the same elements. Also, at least in an extension application, DOM accesses (e.g. repeatedly getting the next 'parentNode' in 'ancestors') are very expensive due to X-Rays[4].

It should be noted that this implementation can still benefit from memoization, as the same element (e.g. 'div') could be considered for multiple different 'type's[5].

[1]: https://perfht.ml/30wkWT7
[2]: https://perfht.ml/2Y5FCQ1
[3]: mozilla/price-tracker#319
[4]: https://developer.mozilla.org/en-US/docs/Mozilla/Tech/Xray_vision"
[5]: https://mozilla.github.io/fathom/glossary.html
@biancadanforth
Copy link
Collaborator Author

biancadanforth commented Jul 24, 2019

I have successfully implemented memoization using a Map[1] in an updated isVisible implementation in Price Tracker, but I am getting into an infinite recursion when I try to use Fathom's note method instead.

Here is the experimental branch (built from Price Tracker PR #317 using Fathom 3.0) where I try to use note[2]. Only the last two commits are new. The offending line is when I console.log(fnode.getNote('image') in isVisible.

@erikrose , I see in the Fathom source code that you try to account for infinite recursion already.

  • What is happening here, and is this[2] the right way to use note?
  • How would we incorporate the use of note (or a Map) solution into the Fathom library, since both require some code outside of the isVisible implementation itself?

[1]: Memoizing using a JavaScript Map

const visibleElements = new Map(); // HTML element => isVisible (Boolean) map

// …

  isVisible(fnode) {
    const element = fnode.element;
    const cachedResult = visibleElements.get(element);
    if (cachedResult !== undefined) {
      return cachedResult;
    }
    const rect = element.getBoundingClientRect();
    if (rect.width === 0 || rect.height === 0) {
      visibleElements.set(element, false);
      return false;
    }
    const style = getComputedStyle(element);
    if (style.opacity === '0') {
      visibleElements.set(element, false);
      return false;
    }
    // workaround for https://github.com/w3c/csswg-drafts/issues/4122
    const scrollX = window.pageXOffset;
    const scrollY = window.pageYOffset;
    const absX = rect.x + scrollX;
    const absY = rect.y + scrollY;
    window.scrollTo(absX, absY);
    const newX = absX - window.pageXOffset;
    const newY = absY - window.pageYOffset;
    const eles = document.elementsFromPoint(newX, newY);
    window.scrollTo(scrollX, scrollY);
    const result = eles.includes(element);
    visibleElements.set(element, result);
    return result;
  }

[2] Memoizing using Fathom note WIP

diff --git a/src/extraction/fathom/ruleset_factory.js b/src/extraction/fathom/ruleset_factory.js
index 65fa7d4..1624126 100644
--- a/src/extraction/fathom/ruleset_factory.js
+++ b/src/extraction/fathom/ruleset_factory.js
@@ -2,7 +2,7 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-import {dom, out, rule, ruleset, score, type} from 'fathom-web';
+import {dom, out, rule, ruleset, score, type, note} from 'fathom-web';
 import {euclidean} from 'fathom-web/clusters';
 
 const TOP_BUFFER = 150;
@@ -87,6 +87,7 @@ export default class RulesetFactory {
 
   /** Scores fnode by its vertical location relative to the fold */
   isAboveTheFold(fnode) {
+    console.log(fnode.noteFor('image'));
     const viewportHeight = 950;
     const imageTop = fnode.element.getBoundingClientRect().top;
 
@@ -199,6 +200,7 @@ export default class RulesetFactory {
   }
 
   isVisible(fnode) {
+    console.log(fnode.noteFor('image'));
     const element = fnode.element;
     const rect = element.getBoundingClientRect();
     if (rect.width === 0 || rect.height === 0) {
@@ -258,7 +260,7 @@ export default class RulesetFactory {
        * Image rules
        */
       // consider all visible img elements
-      rule(dom('img').when(this.isVisible.bind(this)), type('image')),
+      rule(dom('img').when(this.isVisible.bind(this)), note(() => ({isVisible: true})).type('image')),
       // and divs, which sometimes have CSS background-images
       // TODO: Consider a bonus for <img> tags.
       rule(dom('div').when(fnode => this.isVisible(fnode) && this.hasBackgroundImage(fnode)), type('image')),

biancadanforth added a commit that referenced this issue Jul 25, 2019
Compared to a baseline profile[1] of Price Tracker's current 'isVisible' implementation (on which Fathom's 'isVisible' method is based), this clickability approach offers a 53% (146 ms) reduction in Fathom-related jank[2] for the same locally hosted sample page.

This is largely due to removing the use of the 'ancestors' Fathom method in 'isVisible'[3], which was performing a lot of redundant layout accesses (and triggering a lot of layout flushes) for the same elements. Also, at least in an extension application, DOM accesses (e.g. repeatedly getting the next 'parentNode' in 'ancestors') are very expensive due to X-Rays[4].

Notes:
* If the proposal to the W3C CSS Working Group[5] is implemented, this clickability approach could forgo the workaround and see as much as 81% (374 ms) reduction in Fathom-related jank[3].
* This implementation can still benefit from memoization, as the same element (e.g. 'div') could be considered for multiple different 'type's[6].

[1]: https://perfht.ml/30wkWT7
[2]: https://perfht.ml/2Y5FCQ1
[3]: mozilla/price-tracker#319
[4]: https://developer.mozilla.org/en-US/docs/Mozilla/Tech/Xray_vision"
[5]: w3c/csswg-drafts#4122
[6]: https://mozilla.github.io/fathom/glossary.html
@biancadanforth
Copy link
Collaborator Author

After talking with Erik, we are limiting this issue to improving isVisible's performance without memoizing (and fixing the existing bug with getComputedStyle().width/getComputedStyle().height). Memoizing is handled by #121 .

biancadanforth added a commit that referenced this issue Jul 29, 2019
…rmance

Compared to a baseline profile[1] of Price Tracker's current 'isVisible' implementation (on which Fathom's 'isVisible' method is based), this clickability approach offers a 53% (146 ms) reduction in Fathom-related jank[2] for the same locally hosted sample page.

This is largely due to removing the use of the 'ancestors' Fathom method in 'isVisible'[3], which was performing a lot of redundant layout accesses (and triggering a lot of layout flushes) for the same elements. Also, at least in an extension application, DOM accesses (e.g. repeatedly getting the next 'parentNode' in 'ancestors') are very expensive due to X-Rays[4].

Notes:
* If the proposal to the W3C CSS Working Group[5] is implemented, this clickability approach could forgo the workaround and see as much as 81% (374 ms) reduction in Fathom-related jank[3].
* This implementation can still benefit from memoization, as the same element (e.g. 'div') could be considered for multiple different 'type's[6].

[1]: https://perfht.ml/30wkWT7
[2]: https://perfht.ml/2Y5FCQ1
[3]: mozilla/price-tracker#319
[4]: https://developer.mozilla.org/en-US/docs/Mozilla/Tech/Xray_vision"
[5]: w3c/csswg-drafts#4122
[6]: https://mozilla.github.io/fathom/glossary.html
biancadanforth added a commit that referenced this issue Aug 3, 2019
Unfortunately, the previous commit's approach based on clickability proved untenable.[1]

A distant second sync solution is to early return where possible and use the cheapest styles first (the second implementation approach[2]), which reduces Fathom jank by 13%*, though there are a couple differences:
* No 'getBoxQuads'. This is an experimental API only enabled on Nightly.
* Checks if the element is off-screen. The Price Tracker implementation was missing this check.

Unfortunately, this implementation still uses 'ancestors', which causes expensive XRays[3] work in extension applications and still triggers layout flushes at suboptimal times. This is something that can be avoided with an async solution to the tune of a 40% reduction in jank using 'requestAnimationFrame' and 'setTimeout'[4].

On the brighter side, it is more correct than the previous implementation, removing 'getComputedStyle().width' and 'getComputedStyle().height' completely and covering more valid cases than before.

*: This is slightly worse than the expected 16%, because my original implementation in Price Tracker did not check for elements off-screen as the Fathom implementation does. Its profile[5] shows:
 - The largest unresponsive chunk is still caused by Fathom extraction, contributing 399 ms of jank right around page load.
 - `isVisible` made up 238 ms (60%) of this jank.
 - This change reduced overall Fathom-related jank by 61 ms (13%) compared to the original implementation of isVisible[2].

[1]: #116 (comment)
[2]: mozilla/price-tracker#319 (comment)
[3]: https://developer.mozilla.org/en-US/docs/Mozilla/Tech/Xray_vision
[4]: mozilla/price-tracker#319 (comment)
[5]: https://perfht.ml/2T0oYQS
biancadanforth added a commit that referenced this issue Aug 9, 2019
Compared to a baseline profile[1] of Price Tracker's current 'isVisible' implementation (on which Fathom's 'isVisible' method is based), this clickability approach offers a 53% (146 ms) reduction in Fathom-related jank[2] for the same locally hosted sample page.

This is largely due to removing the use of the 'ancestors' Fathom method in 'isVisible'[3], which was performing a lot of redundant layout accesses (and triggering a lot of layout flushes) for the same elements. Also, at least in an extension application, DOM accesses (e.g. repeatedly getting the next 'parentNode' in 'ancestors') are very expensive due to X-Rays[4].

Notes:
* If the proposal to the W3C CSS Working Group (see inline comment in patch) is implemented, this clickability approach could forgo the workaround and see as much as 81% (374 ms) reduction in Fathom-related jank[3].
* This implementation can still benefit from memoization, as the same element (e.g. 'div') could be considered for multiple different 'type's[6].

[1]: https://perfht.ml/30wkWT7
[2]: https://perfht.ml/2Y5FCQ1
[3]: mozilla/price-tracker#319
[4]: https://developer.mozilla.org/en-US/docs/Mozilla/Tech/Xray_vision"
[6]: https://mozilla.github.io/fathom/glossary.html
biancadanforth added a commit that referenced this issue Aug 9, 2019
Unfortunately, the previous commit's approach based on clickability proved untenable.[1]

A distant second sync solution is to early return where possible and use the cheapest styles first (the second implementation approach[2]), which reduces Fathom jank by 13%*, though there are a couple differences:
* No 'getBoxQuads'. This is an experimental API only enabled on Nightly.
* Checks if the element is off-screen. The Price Tracker implementation was missing this check.

Unfortunately, this implementation still uses 'ancestors', which causes expensive XRays[3] work in extension applications and still triggers layout flushes at suboptimal times. This is something that can be avoided with an async solution to the tune of a 40% reduction in jank using 'requestAnimationFrame' and 'setTimeout'[4].

On the brighter side, it is more correct than the previous implementation, removing 'getComputedStyle().width' and 'getComputedStyle().height' completely and covering more valid cases than before.

*: This is slightly worse than the expected 16%, because my original implementation in Price Tracker did not check for elements off-screen as the Fathom implementation does. Its profile[5] shows:
 - The largest unresponsive chunk is still caused by Fathom extraction, contributing 399 ms of jank right around page load.
 - `isVisible` made up 238 ms (60%) of this jank.
 - This change reduced overall Fathom-related jank by 61 ms (13%) compared to the original implementation of isVisible[2].

[1]: #116 (comment)
[2]: mozilla/price-tracker#319 (comment)
[3]: https://developer.mozilla.org/en-US/docs/Mozilla/Tech/Xray_vision
[4]: mozilla/price-tracker#319 (comment)
[5]: https://perfht.ml/2T0oYQS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant