Browsers. Magic is inside.

45
Browsers Magic is inside Alex Tokarenko [email protected] om

description

Browser internal components Main processes during page load or dynamic changes Performance tips and tricks Chrome Devtools in action

Transcript of Browsers. Magic is inside.

Page 1: Browsers. Magic is inside.

BrowsersMagic is inside

Alex [email protected]

Page 2: Browsers. Magic is inside.

What we will talk about

• Browser internal components• Main processes during page load or dynamic changes• Performance tips and tricks• Chrome Devtools in action

Page 3: Browsers. Magic is inside.

Why we will talk about it?

• Mostly used software in the world• Internet Explorer 90% dominance

• Nowadays browsers not a "black box“ - they became opensource

Page 4: Browsers. Magic is inside.

High Level structure

Page 5: Browsers. Magic is inside.

Referenced rendering engines

All examples will be from source code ofWebKit, Blink, Gecko

Why? – Because they are open sourced

Page 6: Browsers. Magic is inside.

Rendering engine basic flow

Parse HTML to construct DOM tree

Render tree construction

Layout the render tree

Paint

Page 7: Browsers. Magic is inside.

Main components and processes

Page 8: Browsers. Magic is inside.

Parse HTML to construct DOM tree

Render tree construction

Layout the render tree

Paint

Page 9: Browsers. Magic is inside.

HTML Parser doings

• Parses input HTML tag soup• Fixes web author mistakes• Requests to load resources• Constructs DOM tree

Page 10: Browsers. Magic is inside.

Turning ‘soup’ into DOM tree

Page 11: Browsers. Magic is inside.

HTML Language

• HTML approach is very "forgiving“• HTML is not a context free grammar• Can’t be parsed by XML parser• Can’t be parsed by regular parsers (BNF) • Defined in DTD (Document Type Definition)

Page 12: Browsers. Magic is inside.

Error tolerance example #1

WebKit source code:

if (m_inStrayTableContent && localName == tableTag) popBlock(tableTag);

Page 13: Browsers. Magic is inside.

Error tolerance example #2

• Start with closed tag • Not closed tags at all Handling </BR> in WebKit code:

if (t->isCloseTag(brTag) && m_document->inCompatMode()) {

reportError(MalformedBRError); t->beginTag = true;

}

Page 14: Browsers. Magic is inside.

HTML parsing flow

Page 15: Browsers. Magic is inside.

Special parsing algorithm because

• Forgiving nature of the language• Historically lack of documentation developers• Huge amount of invalid code

HTML parsers 'guesses' the intention of the code author

Page 16: Browsers. Magic is inside.

Resources loading during parsing

• Scripts• CSS• Other resources

Page 17: Browsers. Magic is inside.

Scripts loading VS Page Latency

Script is loaded and executed immediately when achieved

Parsing halts until script execution

Page 18: Browsers. Magic is inside.

Recommendation

• Put the script at the end of document • HTML5 defer and async attributes

Page 19: Browsers. Magic is inside.

CSS Loading VS Latency

Can block scripts execution until loaded

Page 20: Browsers. Magic is inside.

Browsers are smart

Speculative parsers find resources references to load in parallel threads

Page 21: Browsers. Magic is inside.

Parse HTML to construct DOM tree

Render tree construction

Layout the render tree

Paint

Page 22: Browsers. Magic is inside.

Rendering tree

Holds:• Tree of visual elements in display order• Style information, computed metrics• Shadow DOM tree

Page 23: Browsers. Magic is inside.

Rendering tree VS DOM

Page 24: Browsers. Magic is inside.

Out of basic flow

• “display:none” elements are excluded• Absolute and fixed position elements• Non visual elements like <head></head>

Page 25: Browsers. Magic is inside.

Computed style

Page 26: Browsers. Magic is inside.

Performance impact

• Style is a very large construct • Lookup for matching CSS rule can cause performance issues

div div div div { …

}

• Applying rules is complex

Page 27: Browsers. Magic is inside.

Browsers are smart

• Style objects can be shared between render objects

• Browser collect changes and process them on demand

Page 28: Browsers. Magic is inside.

Parse HTML to construct DOM tree

Render tree construction

Layout the render tree

Paint

Page 29: Browsers. Magic is inside.

What is Layout process?

• Calculation of geometry and position• Flow based model (left-to-right, top-to-bottom)• Coordinate system relative to top left

coordinates

Page 30: Browsers. Magic is inside.

How Layout Process Works

• Parent determines its width• Parent places children with right coordinates• Accumulate children their heights• Caches calculated values

Page 31: Browsers. Magic is inside.

Global Layout

• Occurs at least ones for whole tree• Happens on global changes (like window resize)

Page 32: Browsers. Magic is inside.

Incremental Layout

Happens:• When new element added to the tree• When geometric attributes changes

Page 33: Browsers. Magic is inside.

Browser is smart

Usually changes are batched and done asynchronously

However script accessing geometry attributes can force synchronous layout

Page 34: Browsers. Magic is inside.

Synchronous layout

Synchronous layout demo

// Animation loopfunction update(timestamp) {    for(var m = 0; m < movers.length; m++) {        movers[m].style.left = ((Math.sin(movers[m].offsetTop + timestamp/1000)+1) * 500) + 'px';        }    raf = window.requestAnimationFrame(update);};

Page 35: Browsers. Magic is inside.

Painting

• Traversing the tree from the root• Global and Incremental paint• Dirty bit system

Page 36: Browsers. Magic is inside.

Painting order

CSS2 specification defines the order of the painting elements:– background color– background image– border– children– outline

Page 37: Browsers. Magic is inside.

What can trigger REcalculations?

• Changes style will cause restyle and repaint of the element;• Changes of position will cause relayout and repaint;• Adding a DOM node will cause relayout and repaint of the

node.• Major changes will cause invalidation of caches, relayout

and repaint

Page 38: Browsers. Magic is inside.

Recommendations

o Cache style values if possible for reado Change Non-visible element and set it to visibleo Use documentFragment or cloned element and then swap it with

old oneo Use classes instead of inline styleso Try to keep changes lower in the tree

Page 39: Browsers. Magic is inside.

How we make a deal with all this stuff?!

• Browser dev tools– Timeline– Logs– Heap profiler– Object allocations– CPU Profiler

Page 40: Browsers. Magic is inside.

Links

• http://www.html5rocks.com/en/tutorials/internals/howbrowserswork/• http://taligarsiel.com/Projects/howbrowserswork1.htm• https://developers.google.com/chrome-developer-tools/docs/demos/too-much-layout/• http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/• https://www.webkit.org/blog/114/webcore-rendering-i-the-basics/• http://www.chromium.org/blink• http://msdn.microsoft.com/en-us/library/aa741312(v=vs.85).aspx• https://lists.webkit.org/pipermail/webkit-dev/2013-April/024436.html• http://stackoverflow.com/questions/15804169/the-safari-javascript-engine-in-webkit• http://www.html5rocks.com/en/tutorials/speed/script-loading/• http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html• http://royal.pingdom.com/2013/03/21/browser-wars-2013/• http://www.html5rocks.com/en/tutorials/memory/effectivemanagement• http://www.html5rocks.com/en/tutorials/speed/static-mem-pools• http://www.html5rocks.com/en/tutorials/performance/mystery/• http://en.wikipedia.org/wiki/V8_(JavaScript_engine)• http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/• https://code.google.com/p/v8/

Page 41: Browsers. Magic is inside.

Q?

Page 42: Browsers. Magic is inside.

Join us

Page 43: Browsers. Magic is inside.

Если Вам захотелось присоединиться к команде Devexperts,

пишите и звоните нам:

Тел.: (812) 438-16-26

E-mail: [email protected]

Вакансии: hh.ru и itmozg.ru.

Наши новости: devexperts.com и ВКонтакте.

Контакты

Page 44: Browsers. Magic is inside.

Мы создаем качественное и эффективное ПО для

комплексной автоматизации брокерской, биржевой и финансовой

деятельности

Devexperts

Page 45: Browsers. Magic is inside.

Наша команда – это 300 профессионалов в области программирования,

тестирования и поддержки ПО