浏览器实现移动端高性能css3动画(开启gpu加速)

2020-05-02 08:33:59易采站长站整理

复制代码
// 触发两次 layout
var newWidth = aDiv.offsetWidth + 10; // Read
aDiv.style.width = newWidth + ‘px’; // Write
var newHeight = aDiv.offsetHeight + 10; // Read
aDiv.style.height = newHeight + ‘px’; // Write

// 只触发一次 layout
var newWidth = aDiv.offsetWidth + 10; // Read
var newHeight = aDiv.offsetHeight + 10; // Read
aDiv.style.width = newWidth + ‘px’; // Write
aDiv.style.height = newHeight + ‘px’; // Write

从注释中可找到规律,连续的读取offsetWidth/Height属性与连续的设置width/height属性,相比分别读取设置单个属性可少触发一次layout。
从结论看似乎与执行队列有关,没错,这是浏览器的优化策略。所有可触发layout的操作都会被暂时放入 layout-queue 中,等到必须更新的时候,再计算整个队列中所有操作影响的结果,如此就可只进行一次的layout,从而提升性能。
关键一,可触发layout的操作,哪些操作下会layout的更新(也称为reflow或者relayout)?
我们从浏览器的源码实现入手,以开源Webkit/Blink为例, 对layout的更新,Webkit 主要通过 Document::updateLayout 与Document::updateLayoutIgnorePendingStylesheets 两个方法:

复制代码
void Document::updateLayout()
{
ASSERT(isMainThread());

FrameView* frameView = view();
if (frameView && frameView->isInLayout()) {
ASSERT_NOT_REACHED();
return;
}

if (Element* oe = ownerElement())
oe->document()->updateLayout();

updateStyleIfNeeded();

StackStats::LayoutCheckPoint layoutCheckPoint;

if (frameView && renderer() && (frameView->layoutPending() || renderer()->needsLayout()))
frameView->layout();

if (m_focusedNode && !m_didPostCheckFocusedNodeTask) {
postTask(CheckFocusedNodeTask::create());
m_didPostCheckFocusedNodeTask = true;
}
}

void Document::updateLayoutIgnorePendingStylesheets()
{
bool oldIgnore = m_ignorePendingStylesheets;

if (!haveStylesheetsLoaded()) {
m_ignorePendingStylesheets = true;

HTMLElement* bodyElement = body();
if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
m_pendingSheetLayout = DidLayoutWithPendingSheets;
styleResolverChanged(RecalcStyleImmediately);
} else if (m_hasNodesWithPlaceholderStyle)
recalcStyle(Force);
}

updateLayout();

m_ignorePendingStylesheets = oldIgnore;
}

从 updateLayoutIgnorePendingStylesheets 方法的内部实现可知,其也是对 updateLayout 方法的扩展,并且在现有的 layout 更新模式中,大部分场景都是调用 updateLayoutIgnorePendingStylesheets 来进行layout的更新。