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

Perf: Optimise resizerObservers setup #1325

Merged
merged 4 commits into from
Aug 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 25 additions & 20 deletions packages/child/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -747,35 +747,40 @@ The <b>size()</> method has been deprecated and replaced with <b>resize()</>. U
}, 0)
}

const checkPositionType = (el) => {
if (el?.nodeType !== Node.ELEMENT_NODE) return false

const style = getComputedStyle(el)

return style?.position !== '' && style?.position !== 'static'
}
const resizeSet = new WeakSet()

const attachResizeObserverToNonStaticElements = (el) => {
if (el?.nodeType !== Node.ELEMENT_NODE) return null
// This function has to iterate over all page elements during load
// so is optimized for performance, rather than best practices.
function attachResizeObserverToNonStaticElements(rootElement) {
if (rootElement.nodeType !== Node.ELEMENT_NODE) return

if (!resizeSet.has(rootElement)) {
const position = getComputedStyle(rootElement)?.position
if (!(position === '' || position === 'static')) {
resizeObserver.observe(rootElement)
resizeSet.add(rootElement)
log(`Attached resizeObserver: ${getElementName(rootElement)}`)
}
}

return [...getAllElements(el)()]
.filter(checkPositionType)
.forEach(setupResizeObserver)
}
const nodeList = getAllElements(rootElement)()

const resizeSet = new WeakSet()
// eslint-disable-next-line no-restricted-syntax
for (const node of nodeList) {
if (resizeSet.has(node) || node?.nodeType !== Node.ELEMENT_NODE) continue // eslint-disable-line no-continue
Dismissed Show dismissed Hide dismissed

function setupResizeObserver(el) {
if (resizeSet.has(el)) return
const position = getComputedStyle(node)?.position
if (position === '' || position === 'static') continue // eslint-disable-line no-continue

resizeObserver.observe(el)
resizeSet.add(el)
log(`Attached resizeObserver: ${getElementName(el)}`)
resizeObserver.observe(node)
resizeSet.add(node)
log(`Attached resizeObserver: ${getElementName(node)}`)
}
Dismissed Show dismissed Hide dismissed
}

function setupResizeObservers() {
resizeObserver = new ResizeObserver(resizeObserved)
setupResizeObserver(document.body)
resizeObserver.observe(document.body)
attachResizeObserverToNonStaticElements(document.body)
}

Expand Down
Loading