gpt4 book ai didi

javascript - 如何对强制回流的 Javascript 操作进行分组?

转载 作者:行者123 更新时间:2023-12-04 14:53:15 26 4
gpt4 key购买 nike

我有一个项目负责管理元素的渲染,但我遇到了替换元素然后专注于之前关注的任何内容的性能问题。

下面是一个复制性能问题的最小示例:

const renderPage = () => {
// get the old section element
const oldSection = document.querySelector('section')

// create a new section element (we'll replaceWith later)
const newSection = document.createElement('section')

// create the render button
const newButton = document.createElement('button')
newButton.innerHTML = 'Render Page'
newButton.onclick = renderPage
newSection.appendChild(newButton)

// create a bunch of elements
const dummyDivs = [...new Array(100000)].forEach(() => {
const dummy = document.createElement('div')
dummy.innerHTML = 'dummy'
newSection.appendChild(dummy)
})

// replace the old page with the new one (causes forced reflow)
oldSection.replaceWith(newSection)
// reattach focus on the button (causes forced reflow)
newButton.focus()
}

window.renderPage = renderPage
<section>
<button onclick="renderPage()">Render</button>
</section>

在本地运行时,我在 Chrome/Edge 的性能报告中看到以下内容 Performance Report, forced reflow is highlighted under both a replaceWith and focus event

replaceWithfocus 都会触发强制重排。有没有办法对这些操作进行批处理或分组,以便只发生一次回流?我意识到根本没有办法真正解决这种情况,但如果我可以对它们进行批处理,我认为这可能会提高我的性能。

最佳答案

事实上,焦点总是导致回流:What forces layout / reflow

所以你可以做的是通过独立插入新按钮来减少回流时间,启动焦点,然后你可以附加其他 child :

工作示例:Example

const renderPage = () => {
// get the old section element
const oldSection = document.querySelector('section')

// create a new section element (we'll replaceWith later)
const newSection = document.createElement('section')

// create the render button
const newButton = document.createElement('button')
newButton.innerHTML = 'Render Page'
newButton.onclick = renderPage
newSection.appendChild(newButton)

// create a bunch of elements
const dummies = []; // store in seperate array
const dummyDivs = [...new Array(100000)].forEach(() => {
const dummy = document.createElement('div')
dummy.innerHTML = 'dummy';
dummies.push(dummy)
})
// insert new section only with new button
oldSection.replaceWith(newSection)
newButton.focus(); // always causes reflow; but fast because it's only one element
// store all other nodes after focus
newSection.append(...dummies)
}

window.renderPage = renderPage

关于javascript - 如何对强制回流的 Javascript 操作进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68675817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com