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

Performance issue: getMatchedCSSRules takes ~800ms, causing slowdowns during split operations #803

Open
francesc79 opened this issue Nov 29, 2024 · 1 comment

Comments

@francesc79
Copy link

Hi,

I am experiencing a performance issue related to the getMatchedCSSRules method. During split operations, this method takes approximately 800ms to execute, causing noticeable slowdowns. In the image attached you can see a problem.

split

Have you considered adding a cache to this method or passing with options the value required for avoid search in all css rules?

Looking forward to your feedback

@mrjjwright
Copy link

here is what i did in my TS fork:

const ruleCache = new WeakMap<Element, CSSStyleRule[]>()

export function getMatchedCSSRules(el: Element): CSSStyleRule[] {
  // Check cache first
  const cached = ruleCache.get(el)
  if (cached) {
    return cached
  }

  const matchedRules: CSSStyleRule[] = []
  const sheets = Array.from(el.ownerDocument.styleSheets)

  // Process each stylesheet
  for (const sheet of sheets) {
    try {
      const rules = Array.from(sheet.cssRules || []) as CSSStyleRule[]

      // Batch process rules using filter
      const matches = rules.filter((rule) => {
        try {
          return el.matches(rule.selectorText)
        } catch {
          return false
        }
      })

      matchedRules.push(...matches)
    } catch {
      // Ignore security errors from cross-origin stylesheets
      continue
    }
  }

  // Cache the results
  ruleCache.set(el, matchedRules)
  return matchedRules
}

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

2 participants