Sunday, 24 November 2019

Understanding reflow and repaint in HTML

A repaint occurs when changes are made to an elements skin that changes visibly, but do not affect its layout.
Examples of this include outline, visibility, background, or color. According to Opera, repaint is expensive because the browser must verify the visibility of all other nodes in the DOM tree.

A reflow is even more critical to performance because it involves changes that affect the layout of a portion of the page (or the whole page).
A reflow computes the layout of the page. A reflow on an element recomputes the dimensions and position of the element, and it also triggers further reflows on that element’s children, ancestors and elements that appear after it in the DOM. Then it calls a final repaint. Reflowing is very expensive.
Examples that cause reflows include: adding or removing content, explicitly or implicitly changing width, height, font-family, font-size and more.
Other examples:
  • Resizing the window
  • Changing the font
  • Adding or removing a stylesheet
  • Content changes, such as a user typing text in
    an input box
  • Activation of CSS pseudo classes such as :hover (in IE the activation of the pseudo class of a sibling)
  • Manipulating the class attribute
  • A script manipulating the DOM
  • Calculating offsetWidth and offsetHeight

Example of something that will cause reflow

for (let i = 1; i <= 100; i++ {
const newEle = document.createElement('p');
newEle.textContent = 'newly created paragraph element';

document.body.appendChild(newEle);
}

The above code is very inefficient, causing 100 reflow processes for every new paragraph element appended.

You can mitigate this computationally stressful process by using .createDocumentFragment()

const docFrag = document.createDocumentFragment();

const docFrag = document.createDocumentFragment();

 for (let i = 1; i <= 100; i++ {
    const newEle = document.createElement('p');
    newEle.textContent = 'newly created paragraph element';

    docFrag.appendChild(newEle);
    }

document.body.appendChild(docFrag);
The above code will now instead only use the reflow process 1x for the creation of 100 new paragraph elements.



Ohh, then how to get rid of reflow?

Reflows can be top-down or bottom-up as reflow information is passed to surrounding nodes. Reflows are unavoidable, but you can reduce their impact
  1. Change classes on the element you wish to style (as low in the dom tree as possible)
  2. Avoid setting multiple inline styles
  3. Apply animations to elements that are position fixed or absolute
  4. Trade smoothness for speed
  5. Avoid tables for layout
  6. Avoid JavaScript expressions in the CSS (IE only)
1.  Change classes as low in the dom tree as possible and thus limit the scope of the reflow to as few nodes as possible. For example, you should avoid changing a class on wrapper elements to affect the display of child nodes. Object oriented css always attempts to attach classes to the object (DOM node or nodes) they affect, but in this case it has the added performance benefit of minimizing the impact of reflows.

2. Avoid setting multiple inline styles which would each cause a reflow, the styles should be combined in an external class which would cause only one reflow when the class attribute of the element is manipulated.

3. Apply animations with position fixed or absolute: . They don’t affect other elements layout, so they will only cause a repaint rather than a full reflow

4. Trade smoothness for speed: Opera also advises that we trade smoothness for speed. What they mean by this is that you may want to move an animation 1 pixel at a time, but if the animation and subsequent reflows use 100% of the CPU the animation will seem jumpy as the browser struggles to update the flow. Moving the animated element by 3 pixels at a time may seem slightly less smooth on very fast machines, but it won’t cause CPU thrashing on slower machines and mobile devices.

5. Avoid tables for layout (or set table-layout fixed): tables often require multiple passes before the layout is completely established because they are one of the rare cases where elements can affect the display of other elements that came before them on the DOM. Imagine a cell at the end of the table with very wide content that causes the column to be completely resized. This is why tables are not rendered progressively in all browsers.  According to Mozilla, even minor changes will cause reflows of all other nodes in the table.



Useful Resources:
https://csstriggers.com/
http://www.stubbornella.org/content/2009/03/27/reflows-repaints-css-performance-making-your-javascript-slow/
https://stackoverflow.com/questions/2549296/whats-the-difference-between-reflow-and-repaint

Sunday, 17 November 2019

Timing tab of chrome dev tools

Timing breakdown phases explained

Here's more information about each of the phases you may see in the Timing tab:

  • Queueing (no-color, transparent, white). The browser queues requests when:
    • The request was postponed by the rendering engine because it's considered lower priority than critical resources (such as scripts/styles). This often happens with images.
    • The request was put on hold to wait for an unavailable TCP socket that's about to free up.
    • The request was put on hold because the browser only allows six TCP connections per origin on HTTP 1.
    • Time spent making disk cache entries (typically very quick.)
  • Stalled/Blocking (grey). Time the request spent waiting before it could be sent. It can be waiting for any of the reasons described for Queueing. Additionally, this time is inclusive of any time spent in proxy negotiation.
  • Proxy Negotiation (grey):Time spent negotiating with a proxy server connection.
  • DNS Lookup (Dark green). Time spent performing the DNS lookup. Every new domain on a page requires a full roundtrip to do the DNS lookup.
  • Initial Connection / Connecting (Orange):Time it took to establish a connection, including TCP handshakes/retries and negotiating a SSL.
  •  SSL (Orange, but I saw pink on chrome):Time spent completing a SSL handshake.
  •  Request Sent / Sending (Green)Time spent issuing the network request. Typically a fraction of a millisecond.
  • ServiceWorker Preparation. The browser is starting up the service worker.
  • Request to ServiceWorker. The request is being sent to the service worker.
  • Waiting (TTFB) (Green). The browser is waiting for the first byte of a response. TTFB stands for Time To First Byte. This timing includes 1 round trip of latency and the time the server took to prepare the response.
  • Content Download (Blue). The browser is receiving the response. If you see lots of time spent in the Content Download phases, then improving server response or concatenating won't help. The primary solution is to send fewer bytes.
  • Receiving Push. The browser is receiving data for this response via HTTP/2 Server Push.
  • Reading Push. The browser is reading the local data previously received.




SSL handshaking - Both one way and two way

If you have ever browsed an HTTPS URL through a browser, you have experienced the SSL handshake. Even though might not notice it, the browser and the website is creating an HTTPS connection using one-way SSL handshake.
The main purpose of an SSL handshake is to provide privacy and data integrity for communication between a server and a client. During the Handshake, server and client will exchange important information required to establish a secure connection.
There are two types of SSL handshakes described as one-way SSL and two-way SSL (Mutual SSL). Difference between those two is that in one -way SSL only the server authenticates to the client whereas, in two-way SSL, both server and client authenticate to each other. Usually, when we browse an HTTPS website, one-way SSL is being used where only our browser (client) validates the identity of the website (server). Two-way SSL is mostly used in server to server communication where both parties need to validate the identity of each other.

SSL Certificate works on a TCP (Transmission Control Protocol) protocol to send data over the internet. SSL follows a handshake process that sets up a secure connection without disturbing customers’ shopping experience. The SSL handshake process is as under:

After building a TCP connection, the client started the handshake with sending information like SSL version, cipher suites, and compression method.
The server then checks for the highest SSL version that is supported by both of them.
The server also chooses the compression method and the cipher suite from the client’s option.
After this exchange, the server sends a certificate (public key) to the client.
The client confirms the certificate, creates pre-master secret for the session, and encrypts the session with the server’s public key.
The server receives pre-master secret and decrypt it with the private key.
Both parties agree on a single cipher suite and generate the session keys (symmetric keys) to encrypt and decrypt the information during an SSL session.
Finally, both client and server exchanges encrypted message to ensure that the future messages will be encrypted.


https://cheapsslsecurity.com/blog/what-is-ssl-tls-handshake-understand-the-process-in-just-3-minutes/

https://www.ssl2buy.com/wiki/how-does-an-ssl-certificate-work

https://medium.com/@kasunpdh/ssl-handshake-explained-4dabb87cdce

What is TCP? why TCP connection is required in http requests?




Three way handshake:

1. A ------SYN------> B
2. B ---SYN + ACK---> A
3. A ------ACK------>  B


Detailed version:
1. A ------(SEQ = 100, CTL = SYN)------> B
2. B ---(SEQ=300, ACK=101, CTL=(SYN, ACK)---> A
3. A ------(ACK=301, SEQ=101, CTL=ACK)------>  B

The sequence number is the byte number of the first byte of data in the TCP packet sent (also called a TCP segment).
The acknowledgement number is the sequence number of the next byte the receiver expects to receive. The receiver ack'ing sequence number x acknowledges receipt of all data bytes less than (but not including) byte number x.








Note: There is no such machanism in UDP, this is all based on TCP

Thus the TCP handshaking is required for handshaking and flow control.

src:
https://www.youtube.com/watch?v=LyDqA-dAPW4

https://networkengineering.stackexchange.com/questions/24068/why-do-we-need-a-3-way-
handshake-why-not-just-2-way

http://www.cs.miami.edu/home/burt/learning/Csc524.032/notes/tcp_nutshell.html

Storage of a web-browser

Browsers support storage mechanisms such as localStorage, IndexedDB, WebSQL and FileSystem. It is a small database created on the local drive of the computer where the browser is installed. It manages user data such as cache, cookies, bookmarks and preferences.

How to optimise performance of a web-site or mobile site

These are all the points which can boost up your website performance. Below are just bullet points. I'll be touching each of these point every week. Stay tuned for more info.

  1. Http2 multiplexing, header compression and other features like server push
  2. Rather than showing a loader, show a rendered page(did not mean interactive). Something like server side rendering.
  3. Adding more to point 2. Push interactive state away and try to render as early as possible.
  4. Code chunks, lazy loading.
  5. Css splitting, should be route and component based.
  6. DNS resolution ? 
  7. Omitting option call.
  8. To load only useful code, rest can be loaded later when resources are free.
  9. Minify css
  10. Dns preconnect
  11. Code splitting, js and css
  12. Preloading and prefetching
  13. Image sprite using grunt
  14. Prepond API call
  15. Reduce the number of bundle
  16. JS code which can delayed, should be delayed
  17. MJS
  18. Compression: Gzip vs Brotli
  19. CDN
  20. Critical rendering CSS
  21. Service worker: Caching, prefetching
  22. Web worker: using multiple threads
  23. DNS prefetching
  24. DNS resolution using same domain and then redirection to the actual domain
  25. Service worker prefetching

Sunday, 3 November 2019

AMP Pages | Accelerated Mobile Pages

Accelerated Mobile Page (or AMP, for short) is a project from Google and Twitter designed to make really fast mobile pages. At its essence, it's basically a stripped-down form of HTML, a diet HTML


Absolutely. So as Will said, it's like a diet HTML. So certain tags of HTML you just can't use. Things like forms, that are out. You also need to use a streamlined version of CSS. You can use most of CSS, but some parts are falling under best practice and they're just not allowed to be used. Then JavaScript is basically not allowed at all. You have to use an off-the-shelf JavaScript library that they provide you with, and that provides things like lazy loading

And then all of this is designed to be really heavily cached so that Google can host these pages, host your actual content right there, and so they don't even need to fetch it from you anymore.



Why AMPs are so pupular


1. Never stop the content

In regular html parsing, an external script can halt the parsing of the document. But in AMP, external js are now allowed.
AMP never halts parsing. It downloads all its resources in parallel.

2. Asset-indepandant Layout (Static resources layouting)

All the external resources like images, iframes have to mention their size in html so that AMP can know their positioning prior to their load

3. Inline size-bound CSS

Only one inline css allowed. Removes the need for extra http req for external css

4. Efficient font triggering

AMP pages requires zero http request before font start downloading. SInce JS is asynchronous, css is inline.

5. Minimize style and layout recalculations

same as point #2

6. GPU accelerated animations

AMP pages allow to animate only properies which can be handled by only GPU. Namely transform and opacity.

7. Prioritize resource loading

Download the most imp. resource first. Imagess and ads are downloaded only if they are in view port or user is likely to scroll through them.

Resources are loaded as late as possible, but prefetched as early as possible.
Srcs:



src:
1. https://moz.com/blog/accelerated-mobile-pages-whiteboard-friday
2. https://www.youtube.com/watch?v=9Cfxm7cikMY&list=PLXTOW_XMsIDQf5mXiTT6MhdYluziN7dwP