Skip to content

Commit

Permalink
Added perf optimization when a lot of mutations occur at once.
Browse files Browse the repository at this point in the history
  • Loading branch information
getvictor committed Jun 29, 2024
1 parent e20d8e3 commit 06a1b88
Showing 1 changed file with 33 additions and 11 deletions.
44 changes: 33 additions & 11 deletions src/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ let blursCount = maxBlursCount
const performanceOptimizationResetMs = 5 * 1000
let performanceOptimizationMode = false

// For debug
const performanceLogging = false

console.debug("OpenBlur content script loaded")

function unhideBody(force?: boolean) {
Expand Down Expand Up @@ -278,21 +281,40 @@ function unblurElement(elem: HTMLElement) {
}

const observer = new MutationObserver((mutations) => {
const startTime = performance.now()
let addedNodesFound = false
mutations.forEach((mutation) => {
if (mutation.addedNodes.length > 0) {
addedNodesFound = true
mutation.addedNodes.forEach((node) => {
processNodeWithParent(node)
})
} else {
processNodeWithParent(mutation.target)
}
})
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
// Performance optimization: for a lot of mutations, we do a full scan instead.
if (mutations.length > 50) {
processNode(document, new Set<HTMLElement>())
addedNodesFound = mutations.some((mutation) => {
return mutation.addedNodes.length > 0
})
} else {
mutations.forEach((mutation) => {
if (mutation.addedNodes.length > 0) {
addedNodesFound = true
mutation.addedNodes.forEach((node) => {
processNodeWithParent(node)
})
} else {
processNodeWithParent(mutation.target)
}
})
}
if (addedNodesFound) {
setCssSelectors(localConfig.cssSelectors ?? [])
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (performanceLogging) {
const duration = performance.now() - startTime
if (duration > 2) {
console.log(
"OpenBlur MutationObserver took %f ms for mutations",
duration,
mutations,
)
}
}
})

function inputEventListener(event: Event) {
Expand Down

0 comments on commit 06a1b88

Please sign in to comment.