Skip to content

Instantly share code, notes, and snippets.

@iansan5653
Last active May 29, 2026 17:50
Show Gist options
  • Select an option

  • Save iansan5653/f80e82d5fdfa1dc75a4b9a506bbf044b to your computer and use it in GitHub Desktop.

Select an option

Save iansan5653/f80e82d5fdfa1dc75a4b9a506bbf044b to your computer and use it in GitHub Desktop.
Snippet to locate non-visible DOM trees on a page which could be candidates for removal
const result = []
let totalVisibleElements = 0
let totalHiddenElements = 0
const ignoredTags = new Set(["SCRIPT", "STYLE", "LINK", "TEMPLATE"])
const passthroughTags = new Set(['RAILS-PARTIAL'])
/* recursive */
function findHiddenElementTrees(parent) {
for (const child of parent.children) {
if (ignoredTags.has(child.tagName)) {
continue
}
if (passthroughTags.has(child.tagName)) {
findHiddenElementTrees(child)
continue
}
const rect = child.getBoundingClientRect()
if (rect.height === 0 || rect.width === 0) {
const treeSize = child.querySelectorAll("*").length + 1
totalHiddenElements += treeSize
result.push({parent: child, treeSize: treeSize})
} else {
totalVisibleElements++
findHiddenElementTrees(child)
}
}
}
findHiddenElementTrees(document.body)
result.sort((a, b) => a.treeSize - b.treeSize)
console.group("Hidden element trees by size")
let lastTreeSize = null
for (const entry of result) {
if (entry.treeSize !== lastTreeSize) {
if (lastTreeSize !== null) console.groupEnd(`${lastTreeSize} elements`)
lastTreeSize = entry.treeSize
console.groupCollapsed(`${lastTreeSize} elements`)
}
console.log(entry.parent)
}
console.groupEnd(`${lastTreeSize} elements`)
console.groupEnd("Hidden element trees by size")
console.log(`${totalHiddenElements} hidden out of ${totalVisibleElements + totalHiddenElements} total renderable elements (${Math.round((totalHiddenElements / (totalVisibleElements + totalHiddenElements)) * 10000) / 100}% hidden)`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment