Event Loop and Web Performance V2 Flashcards

1
Q

List 3 microtasks

A
  • Promises (resolving or rejecting)
  • Mutation Observer callbacks
  • process.nextTick() (Node.js)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

List atleast 4 macrotasks

A
  • setTimeout()
  • setInterval()
  • I/O operations (e.g. reading/writing files, making HTTP requests)
  • UI rendering and user input handling
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does the event loop work in the context of this code snippet —-

console.log('Start');

setTimeout(() => console.log('Timeout'), 0);

Promise.resolve().then(() => console.log('Promise'));

console.log('End');
A

Here’s how the event loop works in this example:

  • The initial synchronous task (console.log(‘Start’)) is executed and its output is printed to the console.
  • The setTimeout() call is encountered and it schedules the “Timeout” callback to the macrotask queue. Since it’s a macrotask, it will be executed after all microtasks are processed.
  • The Promise is encountered and it schedules its callback to the microtask queue. Since it’s a microtask, it will be executed before any macrotasks.
  • The final synchronous task (console.log(‘End’)) is executed and its output is printed to the console.
  • The microtask queue is checked and the Promise callback is executed, outputting “Promise”.
  • The macrotask queue is checked and the “Timeout” callback is executed, outputting “Timeout”.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Explain the event loop in the context of the code snippet shown below —-

const fs = require('fs');

console.log('Start');

fs.readFile('data.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

console.log('End');
A

In this example, we use the fs.readFile() method to read the contents of a file asynchronously. The callback function is executed when the file has been read, and it outputs the contents of the file to the console.

Here’s how the event loop works in this example:

  • The initial synchronous task (console.log(‘Start’)) is executed and its output is printed to the console.
  • The fs.readFile() call is encountered and it schedules an I/O operation to read the file to the OS.
  • The final synchronous task (console.log(‘End’)) is executed and its output is printed to the console.
  • While the OS is reading the file, the event loop is free to handle other tasks.
  • When the file has been read, the OS signals the event loop to execute the callback function with the file contents.
  • The callback function is executed and its output is printed to the console.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

main goal of the event loop ?

A

the event loop allows JavaScript to execute tasks asynchronously and handle I/O operations in a non-blocking way, improving performance and responsiveness.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

explain the node js event loop in here —–
~~~

console.log(‘start’);

process.nextTick(() => {
console.log(‘next tick callback’);
});

console.log(‘end’);

~~~

A

In this example, we use the process.nextTick() function to defer the execution of a callback until the next iteration of the event loop. We also use the console.log() function to print messages to the console.

When we run this code in Node.js, the following happens:

  • The message “start” is printed to the console.
  • The process.nextTick() function is called, and the callback function is added to the “next tick queue”.
  • The message “end” is printed to the console.
  • The current iteration of the event loop finishes, and the “next tick queue” is processed.
  • The callback function is executed, and the message “next tick callback” is printed to the console.

Note that the callback function is executed after all synchronous code has finished executing, even though it was scheduled before the “end” message was printed to the console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

purpose of next tick queue

A

The “next tick queue” is useful for ensuring that a callback is executed after all synchronous code has finished executing, without blocking the event loop.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

key difference between the event loop in Node.js and the browser

A

One key difference between the event loop in Node.js and the browser is the addition of the “next tick” queue. This queue allows developers to schedule a callback function to run on the next iteration of the event loop, rather than waiting for the current task to finish. This can be useful for breaking up long-running operations or for ensuring that certain code runs before other code in the event loop.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

purpose of google lighthouse

A

audit web pages for performance, accessibility, and other best practices.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What does a google lighthouse generated report contain ?

A

the report contains details in regards to performance, accessibility of a web page; it also contains recommendations for improving the quality of a web page.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Why would you use a PageSpeed Insights API client library ?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Before V8 hidden classes, how were object properties stored in javascript ?

A

JavaScript engines used dictionaries or hash maps to store object properties

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What was the turning point in the JS story that led to the birth of V8 hidden classes ?

A

slower property access times in regards to dictionaries / hash maps

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

When would V8 classes be shared amongst two or more objects ?

A

If multiple objects share the same structure and have the same set of properties, they can share the same hidden class, improving memory efficiency.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

purpose of using V8 hidden classes

A

faster execution times and improved overall performance of JavaScript applications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

purpose of browser cache ?

A

By using the browser cache, we can improve the performance of web pages by reducing the number of requests that need to be made to the server.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Where is the browser cache located ?

A

on the user’s device

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Which API can be used to interact with the browser cache ?

A

Cache API

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

purpose of service workers ?

A

Service workers are scripts that run in the background of a web page, separate from the main thread of the browser. They allow you to cache resources and handle network requests, which can improve the performance and offline functionality of web pages

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

purpose of local storage ?

A

Data storage on a browser irrespective of the fact that the browser window / browser session would stay open.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

purpose of indexed DB ?

A

IndexedDB is a client-side database API that allows web applications to store structured data locally, with indexed access.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

meaning of asynchronous API

A

means that all database operations are non-blocking and use callbacks or promises to handle results

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Is indexed DB synchronous or asynchronous ?

A

async

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

which are the 5 caching strategies in JS?

A
  1. Indexed DB
  2. Local storage
  3. session storage
  4. browser cache / HTTP cache
  5. service workers
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

what are worklets ? What would be some possible use cases ?

A

Worklets are a new type of JavaScript API that allow you to perform heavy computations and animations off the main thread of the browser.

Worklets can be used for a variety of tasks such as animations, audio processing, and more.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

why should you use efficient data structures ?

A

Using efficient data structures can improve performance by reducing the amount of time it takes to access and manipulate data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Name some efficient data structures in JS you can use

A

arrays
sets
maps

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is going on here ?

// HTML code
<ul id="myList">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>

// JavaScript code
const myList = document.getElementById('myList');

myList.addEventListener('click', function(event) {
  if (event.target.tagName === 'LI') {
    console.log('You clicked on ' + event.target.textContent);
  }
});
A

event delegation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is event delegation ?

A

Event delegation is a technique in JavaScript where you attach an event listener to a parent element instead of each individual child element. This is useful when you have a lot of child elements that need the same event listener, as it reduces the amount of code you need to write and can improve performance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What is the purpose of using the for-loop in the code below ?

// create a document fragment
const fragment = document.createDocumentFragment();

// add multiple elements to the fragment
for (let i = 0; i < 10; i++) {
  const li = document.createElement('li');
  li.textContent = 'Item ' + i;
  fragment.appendChild(li);
}

// append the fragment to the DOM
document.getElementById('myList').appendChild(fragment);
A

A document fragment is a lightweight container that allows you to group multiple DOM operations together, which can improve performance by reducing the number of times the DOM is updated.

So the for-loop basically minimizes DOM manipulation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Why are we using map here ?

// create an array of items
const items = ['Item 1', 'Item 2', 'Item 3'];

// create a string of HTML markup
const html = items.map(item => `<li>${item}</li>`).join('');

// append the HTML to the DOM
document.getElementById('myList').innerHTML = html;
A

minimizing DOM manipulation

Use string concatenation or template literals to create HTML markup, and then append it to the DOM all at once. This can be faster than creating individual elements and appending them one at a time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

why should you Cache references to frequently accessed DOM elements ?

A

so you don’t need to search for them every time you need to manipulate them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

purpose of the following code snippet

const concat = require('concat-files');
const uglify = require('uglify-js');

concat(['file1.js', 'file2.js', 'file3.js'], 'combined.js', (err) => {
  if (err) throw err;
  const result = uglify.minify('combined.js');
  console.log(result.code);
});
A

you can combine multiple CSS and JavaScript files into a single file and then minify them to reduce the size of the file. This will help reduce the number of HTTP requests needed to load your webpage.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

purpose of using a performance profiler ?

A

Use a performance profiler to identify bottlenecks in your code. Tools like Chrome DevTools or Firefox Developer Tools can help you identify slow functions, memory leaks, and other performance issues.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

name a couple of perf profilers

A

chrome dev tools
firefox dev tools

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

purpose of lazy loading

A

Lazy loading is a technique where resources are loaded only when they’re needed, instead of all at once. This can improve performance by reducing the amount of time it takes to load the page.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

if yo have the following code snippet in a js file of your web application, what could you do to make sure this function doesn’t block other tasks

function longRunningTask() {
	let result = 0;
	for (let i = 0; i < 100000000; i++) {
		result += i;
	}
	return result;
}
A

you could use a web worker;
Web Workers are a way to run scripts in the background, separate from the main UI thread. This can improve performance by freeing up the UI thread to handle user interactions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

why should you avoid global variables ?

A

Global variables can slow down performance by increasing the amount of memory needed to store data and making it harder to optimize code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

enlist 3 ways of minimizing http requests

A

Combine files, use compression, and use caching to reduce the number of requests.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What is the garbage collector ?

A

In JavaScript, the Garbage Collector (GC) is a built-in mechanism that automatically manages memory allocation and deallocation for objects in the program. It ensures that objects that are no longer needed by the program are identified and removed from memory, freeing up space for new objects and preventing memory leaks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

What does the GC track ?

A

All objects and their references

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What do you mean by reference counting approach for garbage collecting ?

A

This approach keeps track of the number of references to an object. When the reference count drops to zero, the object is no longer reachable and can be garbage collected.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What do you mean by incremental approach for garbage collecting ?

A

This approach breaks the garbage collection process into smaller, incremental steps to avoid freezing the program while the GC is running. It also allows the GC to release memory more frequently, reducing the overall memory footprint of the program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What do you mean by generational approach for garbage collecting ?

A

This approach divides objects into “young” and “old” generations based on their age. Young objects are more likely to be garbage collected because they are short-lived and have a shorter reference chain. Old objects are less likely to be garbage collected because they have a longer reference chain and are more likely to be still in use.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

What is Mark and Sweep ? Where is it mostly used ?

A

Mark and sweep is a garbage collection algorithm.
It is used in programming languages that have automatic memory management.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What is CRP ?

A

The process via which the browser converts the html, js and css code into the visual components of a web page.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What is the 1st CRP step ?

A

HTML PARSING - conversion of the HTML code ( received from the server into the browser ) to the DOM

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

What is the second CRP step?

A

CSS parsing: The browser also receives the CSS code and parses it into a Cascading Style Sheet Object Model (CSSOM).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

What is the 3rd CRP step ?

A

Rendering tree construction: The browser combines the DOM and the CSSOM to create a rendering tree, which is a hierarchical representation of the visual components of the web page. The rendering tree contains all the nodes that need to be displayed on the screen, including text, images, and other elements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

What is the 4rth CRP step ?

A

Layout: The browser calculates the position and size of each node in the rendering tree, based on the CSS styles and layout rules. This process is known as layout, or reflow, and can be time-consuming, especially for complex web pages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

What is the 5th CRP step?

A

Painting: Finally, the browser paints the pixels of the web page on the screen, using the rendering tree and layout information as a guide. This process is known as painting, or rasterization, and involves drawing each element of the web page on the screen.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

Enlist 3 techniques via which CRP can be optimized

A

To optimize the CRP, web developers can use techniques such as:
1. Minimizing the use of blocking resources, such as large images or JavaScript files, that can delay the parsing and rendering of the web page.
2. Using optimized CSS styles and layout rules to minimize the time and complexity of the layout and painting stages.
3. Using modern web development frameworks and tools that optimize the CRP, such as server-side rendering or lazy loading of resources.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

What is LCP ?

A

Largest Contentful Paint (LCP): LCP measures the loading performance of a web page. Specifically, it measures the time it takes for the largest element on the page, such as an image or text block, to become visible to the user.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

What is FID ?

A

First Input Delay (FID): FID measures the interactivity of a web page. Specifically, it measures the time it takes for the page to respond to the user’s first interaction, such as a click or tap.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

What is CLS ?

A

Cumulative Layout Shift (CLS) measures the amount of unexpected layout shifts that occur during the page’s lifetime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

What are core web vitals ?

A

Perf metrics designated by google to analyze the overall performance of a web page

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

What are the 3 metrics measured via core web vitals ?

A

LCP, FID, CLS

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

Enlist 5 ways by which you can optimize core web vitals

A
  • optimizing images and other resources for faster loading,
  • reducing the number of requests made by the page, and
  • optimizing the layout and design of the page to minimize unexpected shifts.
  • using pageSpeed Insights
  • use chrome dev tools
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

Enlist 7 causes for memory leaks in javascript

A
  1. Circular References: When objects reference each other in a circular fashion, without a clear path for garbage collection, they can become “locked” in memory and never be released.
  2. Unused Variables: Variables that are created but never used, or not properly disposed of, can accumulate in memory over time and cause memory leaks.
  3. Event Listeners: When event listeners are not properly removed, they can accumulate and cause memory leaks, especially in long-lived applications.
  4. Timers: Timers that are not properly cleared can continue to run even when they are no longer needed, leading to memory leaks.
  5. Closures: When functions create closures, they can hold on to references to variables and data that are no longer needed, causing memory leaks.
  6. Large Data Structures: Large data structures, such as arrays and maps, can consume a lot of memory and cause leaks if they are not properly managed.
  7. DOM Elements: DOM elements can cause memory leaks if they are not properly removed from the document or if they have circular references.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

What is the first step in the mark and sweep algorithm ?

A

Mark: Mark all the live objects in memory ( objects which have a reference or a chain of reference )

61
Q

What is the second step in the mark and sweep algorithm ?

A

Sweep: Non-live memory is de-allocated leading to more free memory

62
Q

What is the third step in the mark and sweep algorithm ?

A

Compact: compaction of the live objects together to reduce fragmentation

63
Q

Enlist three react perf measurement tools

A

Using the Chrome DevTools Performance tab
Using the React Developer Tools Chrome extension
Using React’s Profiler API

64
Q

What are 5 common optimizations that Next JS provides out of the box ?

A

Server-side rendering
Automatic code-splitting
Route prefetching
File-system routing
CSS-in-JS styling (styled-jsx)

65
Q

What does PRPL stand for ?

A

PRPL stands for Push, Render, Pre-cache, Lazy-load

66
Q

What is the purpose of PRPL ?

A
  • optimize the loading performance if a web page
67
Q

Enlist the 4 steps in the PRPL pattern

A

The PRPL pattern involves the following steps:
1. Push critical resources: Pushing critical resources, such as HTML, CSS, and JavaScript, to the client as soon as possible to reduce the time-to-first-meaningful-paint (TTFP) of the web application.
2. Render initial route: Rendering the initial route of the web application as quickly as possible to provide a fast user experience.
3. Pre-cache remaining routes: Pre-caching remaining routes so that they can be loaded quickly when requested.
4. Lazy-load other resources: Lazy-loading other resources, such as images and videos, to reduce the initial load time of the application.

68
Q

What does RAIL stand for ?

A

RAIL stands for Response, Animation, Idle, and Load,

69
Q

What is the purpose of the RAIL pattern ?

A
  • help in optimizing the overall user experience of web applications
70
Q

What are the 4 steps in the RAIL process ?

A

The RAIL pattern involves the following steps:
1. Response: Ensuring that the web application responds to user input quickly, ideally within 100ms, to provide a fast and responsive user experience.
2. Animation: Ensuring that animations are smooth and run at a consistent frame rate to provide a high-quality user experience.
3. Idle: Optimizing the web application to take advantage of periods of user inactivity to perform resource-intensive tasks, such as prefetching data or pre-caching routes.
4. Load: Ensuring that the web application loads quickly and efficiently, with a goal of loading above-the-fold content within 1 second and the full page within 3 seconds.

71
Q

What is FCP ?

A

FCP (First Contentful Paint) is a performance metric used to measure the time it takes for the first piece of content to appear on a web page after a user requests it. The first piece of content can be any element, such as text, an image, or a video.

72
Q

purpose of FCP ?

A

To calculate / measure the loading performance of a web page

73
Q

How can you optimize FCP ? Enlist 4 ways.

A

To improve FCP in JavaScript, developers can use techniques such as
- lazy loading of resources,
- optimizing images and videos,
- minimizing JavaScript and CSS, and
- caching
- SSR

74
Q

What is that one metric measured by Chrome dev tools which is crucial for web page perfomance analysis ?

A

The Total Blocking Time (TBT) metric

75
Q

What are worklets ?

A

In JavaScript, “worklet” typically refers to the Web Audio API worklet, which allows you to run custom audio processing code on a separate thread.

76
Q

Give 2 use-cases of worklets

A

Interactive Web Audio Applications, Collaborative Audio Applications

77
Q

Name 3 different types of worklets

A

Paint Worklets, Layout Worklets, and Animation Worklets.

78
Q

Enlist 6 use-cases of service workers

A

Here are some of the use cases of service workers in JavaScript:

Offline support: Service workers can cache assets and data to enable offline functionality for web applications. This is useful for applications that need to work in areas with poor or unreliable network connectivity.

Push notifications: Service workers can receive push notifications from a server, even when the web page is not open. This allows web applications to send real-time notifications to users, which can be useful for news updates, messaging apps, and other types of real-time communication.

Background synchronization: Service workers can periodically synchronize data with a server in the background, even when the web page is not open. This allows web applications to stay up-to-date with the latest data, even if the user hasn’t opened the app in a while.

Performance optimization: Service workers can optimize performance by caching frequently used assets and preloading resources for faster load times. They can also provide faster page transitions by serving cached assets during navigation.

Security: Service workers can be used to enforce security policies, such as restricting access to certain resources or enforcing HTTPS for all network requests.

Analytics and tracking: Service workers can be used to collect usage data and analytics in the background, even when the user is not actively using the web page. This can be useful for tracking user behavior and improving the user experience.

79
Q

What term is used by firefox for “layout”

A

reflow

80
Q

3 ways of optimizing layout ?

A
  1. Try to not have too many DOM elements.
  2. Use the new flexbox
  3. Avoid forced synchronous layouts and layout thrashing;
81
Q

scope of the layout process ?

A

Layout is normally scoped to the whole document.

82
Q

What happens when you place too many callbacks in the next tick queue

A

The event loop might get blocked and overloaded

83
Q

How can service workers provide offline support ?

A

Service workers can cache assets and data to enable offline functionality for web applications. This is useful for applications that need to work in areas with poor or unreliable network connectivity.

84
Q

How can service workers help in sending / receiving push notifications ?

A

Service workers can receive push notifications from a server, even when the web page is not open. This allows web applications to send real-time notifications to users, which can be useful for news updates, messaging apps, and other types of real-time communication.

85
Q

How can service workers contribute to analytics and tracking ?

A

Analytics and tracking: Service workers can be used to collect usage data and analytics in the background, even when the user is not actively using the web page. This can be useful for tracking user behavior and improving the user experience.

86
Q

How can service workers enhance security of a web app ?

A
  • enforce security policies
  • restrict access to certain resources
  • enforce HTTPS for all network requests.
87
Q

How can service workers contribute to performance optimization ?

A
  • caching frequently used assets
  • preloading resources for faster load times.
  • provide faster page transitions by serving cached assets during navigation.
88
Q

How can service workers enable web applications to stay up-to-date with the latest server data even when the user hasn’t opened the app in a while ?

A

Service workers can periodically synchronize data with a server in the background, even when the web page is not open

89
Q

How would you use the local storage / session storage while building a shopping cart application ?

A

The cart items can be stored in the storage mechanism and retrieved when the user returns to the website.

90
Q

How would you customize user preferences for a webpage like font ?

A

Local storage or session storage can be used to store user preferences such as language, font size, theme, etc

91
Q

Can session storage / local storage be used while building web forms ? If so, explain how ?

A

saving the form state

92
Q

How would you use the local storage / session storage while building a game web application ?

A

help save the game state

93
Q

How would you use local storage / session storage while integrating auth tokens into your web app ?

A

Authentication token: When a user logs in to a web application, the server can send an authentication token that can be stored in local storage or session storage. This token can be used to authenticate the user for subsequent requests, avoiding the need to repeatedly enter login credentials.

94
Q

E-commerce websites often have a large amount of product data that needs to be stored locally to reduce load times and provide a better user experience. Would you use caching ? Which caching approach would you use ?

A

Indexed DB

95
Q

Social media applications often store a lot of user data, such as profiles, posts, and media. Would you use caching? If so, which caching approach would you use ?

A

Indexed DB

96
Q

Applications that need to work offline, such as email clients or note-taking apps, can benefit from using which caching approach ?

A

Indexed DB ?

97
Q

Progressive web applications (PWAs) are web applications that can be installed and run like native applications. They often have complex user interfaces and rely heavily on caching to provide a smooth experience. Would you use caching? If so, which caching approach would you use ?

A

INDEXED DB

98
Q

Enlist 10 ways in which you can enhance vanilla js performance

A
  • Minimize DOM Manipulation
  • Use Efficient Data Structures
  • Optimize Loops
  • Cache Repeated Computations:
  • Use Event Delegation:
  • Minimize HTTP Requests
  • Use a Performance Profiler
  • Use Lazy Loading
  • Use Web Workers
  • Avoid Global Variables
99
Q

when is indexed DB a good caching strategy ? Give examples

A
  1. E-commerce websites
  2. Social media applications
  3. Offline-capable applications: such as email clients or note-taking apps
  4. Progressive web applications
100
Q

when is Local Storage or Session Storage a good option? Give Examples

A

Whenever you want to share data in between sessions; Below are a few examples —-

  1. Shopping cart
  2. User preferences
  3. Form data
  4. Game state
  5. Authentication token
101
Q

What can be used to perform complex image processing operations, like resizing or filtering images, without blocking the main thread of the browser.

A

Web workers

102
Q

What can be used for computationally intensive data processing tasks, like sorting or filtering large datasets without blocking the main thread ?

A

web workers

103
Q

Main difference between web workers and service workers

A

Web workers are used for parallel computing tasks, while service workers are used for building offline web applications and enhancing the performance of web pages.

104
Q

HTTP cache vs Cache API

A

HTTP cache is controlled by the browser, whereas the Cache API is controlled by the web application. The browser decides which resources to cache based on HTTP headers set by the server, while the web application can decide which resources to cache and for how long using the Cache API.

105
Q

Two ways of setting up HTTP cache ?

A

HTTP cache can be achieved by setting appropriate cache headers on the server-side, or by using a service worker to intercept network requests and cache responses.

106
Q

If the response is successfully retrieved and the HTTP status code is between 200 and 299 (indicating a successful response), what can we say about the http response ?

A

it was cached

107
Q

Which caching mechanism is shown here ?

fetch('https://example.com/resource')
  .then(response => {
    if (response.ok && response.status >= 200 && response.status < 300) {
      if (response.status === 304) {
        console.log('Response was served from the cache');
      } else {
        console.log('Response was not served from the cache');
      }
    }
  })
  .catch(error => {
    console.error('An error occurred:', error);
  });
A

http cache

108
Q

Browser cache vs HTTP cache

A

Browser cache is a component of the HTTP cache that stores responses to HTTP requests made by the browser. It is essentially the same thing as HTTP cache, but it specifically refers to the cache stored on the client-side by the browser.

109
Q

What is an object reference ?

A

A reference is a pointer to an object in memory

110
Q

Why does the GC periodically scan the program memory ?

A

The GC periodically scans the memory and identifies objects that are no longer reachable. These objects are marked for removal and their memory is freed up.

111
Q

What do you mean by a “reachable” object ?

A

an object is considered “reachable” if it can be accessed through a reference from the root of the program, such as a global variable, a local variable in a function, or a property of an object.

112
Q

What is the process of identifying and removing unreferenced objects is called ?

A

garbage collection.

113
Q

Enlist the 3 steps in the Mark and Sweep algorithm

A

The mark and sweep algorithm follows the following steps:
1. Mark: The algorithm starts by marking all the live objects in the heap. This is done by traversing the object graph starting from a set of roots, which are typically the variables in the program’s stack. The algorithm visits every object reachable from the roots and marks them as live.
2. Sweep: After all the live objects have been marked, the algorithm proceeds to sweep through the heap, deallocating any memory that is not marked as live. This memory is then added to a list of free memory blocks that can be used for future allocations.
3. Compact: In some implementations, a third step is added to compact the live objects, moving them closer together in memory to reduce fragmentation.

114
Q

How would you measure FCP start and end time ?

A

When measuring FCP, the start time is typically when the user requests the page, and the end time is when the first piece of content appears on the page.

115
Q

How can you measure FCP ?

A

Performance API

116
Q

What are memory leaks ?

A

Memory leaks occur when a computer program allocates memory for a resource, such as an object, variable, or data structure, but fails to release it when it is no longer needed. Over time, these unreleased memory blocks accumulate and can cause a program to consume an excessive amount of memory, leading to performance degradation and even system crashes.

117
Q

how to detect memory leaks ?

A

tools such as memory profilers and leak detection libraries

118
Q

what is the next step after identifying a memory leak ?

A

Once a leak is identified, developers must fix the underlying code to ensure that all memory is properly managed and released when it is no longer needed.

119
Q

What is the CSSOM ?

A

The CSSOM is a hierarchical representation of the CSS code, which the browser uses to understand the styles and layout of the web page.

120
Q

What is the rendering tree ?

A

is a hierarchical representation of the visual components of the web page.

121
Q

What would be a good LCP score ?

A

.A good LCP score is less than 2.5 seconds.

122
Q

What would be a good FID score ?

A

A good FID score is less than 100 milliseconds.

123
Q

good CLS score ?

A

A good CLS score is less than 0.1.

124
Q

What does the rendering tree contain ?

A

All the nodes of the web page which includes text, images, etc.

125
Q

What are live objects in regards to the mark and sweep algorithm ?

A

Any object which has a reference / chain of reference pointing back to the roots of the tree ( which would mostly be variables )

126
Q

How can you measure the visual stability of a web page ?

A

CLS

127
Q

What does the TBT measure ?

A

The time between the FCP and TTI (time to interactive)

128
Q

What would you call the total amount of time for which the main thread in regards to a web page is blocked enough to prevent input responsiveness ?

A

TBT

129
Q

Which metric optimization should directly improve FID ?

A

TBT

130
Q

Apart from using caching mechanisms to serve static assets, what else could you use ?

A

CDN
Content delivery Network

131
Q

What would you use a CDN for ?

A

To serve static assets

132
Q

What would be a benefit of using CDN ?

A

FCP can be optimized if you use CDN

133
Q

how would you cache static resources ?

A
  • Setting Cache-Control HTTP Headers
  • Using Content Delivery Networks (CDNs)
  • Using ETag Headers
134
Q

What kind of workers is most commonly used to build offline web applications ?

A

Service Workers

135
Q

What kind of mechanism is an ETag ?

A

ETag (Entity Tag) is a mechanism for validating cache freshness.

136
Q

Briefly describe the caching mechanism involved in an ETag

A

When a file changes, the server generates a unique ETag value for that file. The client’s browser sends this ETag value with subsequent requests, and the server can respond with a “304 Not Modified” status if the file hasn’t changed.

137
Q

How does the ETag approach save bandwidth ?

A

This approach saves bandwidth by avoiding unnecessary file transfers when the cached version is still valid.

138
Q

Enlist atleast 5 examples of static resouces

A

Common examples of static resources include:

  • HTML Files: The main structure and content of web pages.
  • CSS Files: Stylesheets that define the visual appearance and layout of web pages.
  • JavaScript Files: Scripts that add interactivity and functionality to web pages.
  • Image Files: Graphics, icons, and photographs displayed on web pages.
  • Font Files: Custom fonts used for text rendering on web pages.
  • Video and Audio Files: Media files embedded or linked within web pages.
  • Document Files: PDFs, Word documents, or other file formats that users can download.
139
Q

Enlist 3 ways of implementing browser cache

A
  • Setting Cache-Control HTTP Headers
  • Using Content Delivery Networks (CDNs)
  • Using ETag Headers
140
Q

What kind of files are we referring to when we say “static resources” ?

A

Static resources, in the context of web development, refer to files that are not dynamically generated by the server for each request but rather remain unchanged or updated infrequently.

141
Q

Which kind of resources are typically served directly to the client’s browser without any processing or manipulation on the server side ?

A

static resources

142
Q

Why are static resources ideal candidates for caching ?

A

Since they do not change frequently

143
Q

Define dynamic resources

A

Dynamic resources, on the other hand, are generated by the server on the fly in response to specific requests and may vary based on user input, database queries, or other factors.

144
Q

give some examples of dynamic resources

A

Examples of dynamic resources include pages with user-specific content, search results, or data fetched from an API.

145
Q

Why are dynamic resources not an ideal candidate for caching purposes ?

A

These resources are typically not cached in the same way as static resources since they can change with each request.

146
Q

How does minification reduce the file size ?

A

minification reduces the file size by removing unnecessary characters

147
Q

How does bundling reduce the number of HTTP requests ?

A

bundling combines multiple JavaScript or CSS files into a single file, to reduce the number of HTTP requests.

148
Q

What are the 4 steps involved in Minification ?

A
  • Removal of whitespace characters
  • Shortening of variable and function names
  • Removal of comments
  • Compression of code