Front-End Tutoring Materials

Browser Rendering

Overall Process

HTML Parsing

CSS Parsing

CSS Object Model (CSSOM)

How about inline CSS?

While HTML defines the structure of the document, it may also reference CSS Stylesheets to define the visual presentation of the document.

 

1. <link rel="stylesheet" />

2. inline <style>

Once the DOM and CSSOM are constructed, the browser can begin the next phase of the pipeline: Style. This phase is sometimes called Recalculate Style or a Render Tree Update.

Render Tree (Layout Tree)

  • A browser-internal C++ data structure that web developers don't directly modify.

  • It is a separate tree from the DOM but often mirrors its structure.

  • Each node typically references a DOM node and a Computed Style.

  • It's essentially composed of every DOM node that should be presented visually on the user's screen.

All the styles that applies to the element, even if there is no CSS specified for that element.

  1. Querying the CSS selectors in the CSSOM for the target DOM element to get the applicable rules.
  2. Resolving any CSS specificity conflicts to the final set of declarations applied:
  • Overrides styles
  • Default styles defined by the browser

CSS Specificity

Although the Render Tree contains all the CSS declarations for widths, heights, colors, etc. for each visual element on the page, the browser has not assigned any geometry or coordinates to the elements.

  • Create and position boxes for each node in the Render Tree.
  • Recursively traverses the newly constructed/updated Render Tree and assigns precise floating-point positions and geometry.
  • Layout is a very deep and complex topic!
  • https://www.youtube.com/watch?v=ZTnIxIA5KGw

Layout (Reflow)

The browser utilizes a computational graphics library to draw the Render Tree nodes programmatically as pixels.

The browser traverses the newly positioned Render Tree recursively, and executes instructions to draw each Render Tree node.

Reflow and Repaint

  • The Repaint occurs when changes are made to the appearance of the elements that change the visibility, but doesn't affect the layout.
    e.g. Visibility, background color, outline
  • Reflow means re-calculating the positions and geometries of elements in the document. The Reflow happens when changes are made to the elements, that affect the layout of the partial or whole page. The Reflow of the element will cause the subsequent reflow of all the child and ancestor elements in the DOM.
    e.g. width, height, font-size

Both Reflow and Repaints are an expensive operation!

Performance Optimization

  • transform
  • opacity
  • will-change
  • Less DOM manipulations by JS

DOMContentLoaded Vs. Load Events

  • DOMContentLoaded Time represents the time it takes to load the HTML structure of the document.
  • Load Time represents the total time it takes to download everything else necessary to display the HTML page.

JS Functions

Ways we declare functions

  • Function Declaration
  • Function Expression
  • The Function() Constructor

function functionName(parameters) {
  // code to be executed
}

 

 

const x = function (a, b) {return a * b};

 

 

const myFunction = new Function("a", "b", "return a * b");

let x = myFunction(4, 3);

Anonymous Function

const x = function (a, b) {return a * b};

  1. These functions cannot be reused.
  2. Debugging is tough because you don’t know the function's name in the call stack.

Self-Invoking Functions (a.k.a. IIFE)

(function () {
  let x = "Hello!!";  // I will invoke myself
})();

Using self-invoking functions we will perform the initialization work only once because after the execution we’ll loose the reference to the function.

(function () {
  // body
}());

 

(function () {
  // body
})();
var module = (function () {
  // private
  return {
    // public
  };
}());

Let's say we want to print from 0 to 5 by a timer. How to fix it?

Closures

https://medium.com/@samueldinesh/javascript-closures-in-2-mins-36d0f3817a0f

function foo() {

  var x = 'Hello'; // local variable

  function bar() { // local function

   console.log(x); // referring to local variable

  };

  return bar;

}

 

var func = foo(); // get the inner function

func(); // prints ‘Hello’

https://rahuldotout.wordpress.com/2011/05/15/professional-javascript-part-5-closures/

Closures are formed when the scope chain of an object survives outside its creation scope.

Why we need closures?

A closure gives you access to an outer function's scope from an inner function.

https://itnext.io/javascript-closure-for-privacy-8a40c274192e

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

A Counter Dilemma

// Initiate counter
let counter = 0;

// Function to increment counter
function add() {
  counter += 1;
}

// Call add() 3 times
add();
add();
add();

myFunction(5);

function myFunction(y) {
  return y * y;
}

Why this works?

Let's move on!

Function Hoisting

  • Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope.
  • Hoisting applies to function declarations and also to variable declarations.

Hoisting & Call Stack

Before we dive into hoisting, let's understand how does Call Stack work in JS.

When a JavaScript programme starts running, the engine creates a Global Execution Context (GEC) and pushes it onto the Call Stack.

https://medium.com/@dhr8v/understanding-javascript-call-stack-event-loop-and-asynchronous-patterns-c4a45f6c78fe

Guess the output.

Exercise 1

var temp = 'hi';
function display() {
    var temp;
    console.log(temp);
    temp = 'bye';
}
display();

It will work just like this way:

Guess the output.

Exercise 2

https://medium.com/@mohdtalib.dev/scope-in-javascript-1cb380bba2a3

Semantic HTML

Semantic HTML Tags

Tags that define the meaning of the content they contain. 

Why Do I Need to Use Semantic HTML Tags?

  • Accessibility
  • SEO
  • Code readability

Common tags we often use

  • header
  • h1~h6
  • hgroup
  • nav
  • main
  • article
  • section
  • aside
  • details
  • time
  • footer
  • figure
  • figcaption

Optimizing Performance (General)

Async & Defer

Trim JavaScript Bundles

Webpack

Measurements

Debugging:
Useful Tips

  1. debugger
  2. console.table
  3. console.timeEnd
  4. Break on node change
  5. Find your DOM elements quickly
  6. Unminify code

2. console.table

3. console.timeEnd

4. Break on change

5. Find your DOM elements quickly

6. Unminify Code

Debugging:
Common Mistakes

  1. Relying solely on console.log statements for debugging
  2. Not testing changes incrementally
  3. Neglecting to document the debugging process
  4. Overlooking error messages
  5. Not testing code in different browsers

Optimizing Performance
(React)

Code Splitting in React

  • Dynamic Import with Webpack
  • React.lazy() with Suspense

Avoid Reconciliation

Reconciliation Pitfalls

  • Avoid Inefficient Rendering: Be cautious with overly complex components or excessive use of useEffect.
  • Immutable Data: Using immutable data structures can simplify reconciliation.
  • React DevTools: Utilize React DevTools to inspect component hierarchies, identify potential reconciliation bottlenecks, and optimize your application's performance.

List Virtualization

Lazy Loading Images

Profiler API

GraphQL with React

GraphQL Structure

Apollo GraphQL

Contentful CMS

Contentful API

Why Apollo Client

HTTP Caching

Caching

https://www.azion.com/en/blog/what-is-http-caching-and-how-does-it-work

HTTP Caching

Advantages to Reusability:

  1. Faster response
  2. Reduces the load on the server

The HTTP cache stores a response associated with a request and reuses the stored response for subsequent requests.

How to setup

HTTP Header

1. Expires

2. cache-control

Quiz

  1. If you only want the client-side to cache, and not intermediate layers like proxy servers, what should you use?
  2. Conversely, if you want proxy servers to also be able to cache data from the backend, what should you use?
  3. Because browsers might automatically cache, if you want absolutely no caching and always want the content to be the latest, what should you use?
  4. What's the difference between cache-control: no-store and cache-control: no-cache?

Cache Validation:
using ETag

with If-None-Match

Cache Validation: using Last-Modified

with If-Modified-Since

Cybersecurity

XSS

  • An XSS (Cross-Site Scripting) attack occurs when a malicious user injects attack scripts from the client side to achieve certain goals, such as stealing cookies, session information, passwords, etc.
  • The most common form of XSS attack involves injecting JavaScript scripts into input fields.

Stored XSS

Reflected XSS

DOM-based XSS

XSS Solutions

  • Preventing Stored and Reflected XSS on backend:
    • Removing keywords related to potential attacks, such as <script> and onerror on backend
  • DOM-based XSS:
    • (HTML Entity for inputs) convert < to &lt;
  • Ensure scripts from users are not executed:
    • implementing a CSP (Content Security Policy)

CSRF

CSRF Solutions

  • Captcha
  • Avoid sensitive requests via GET
  • HTTP Header: Referrer
  • CSRF token
  • SameSite cookies

F2E Tutor Materials

By hinx

F2E Tutor Materials

  • 74