Qs: FrontEnd
What's a frontend design system?
It is a collection of reusable UI components, patterns, and guidelines that ensures consistency, efficiency, and scalability in web or app interfaces.
It’s more than just a component library; it also includes design principles, branding rules, accessibility standards, and often a shared codebase.
Key aspects:
Core Components - i.e. Buttons, Inputs, Modals, Cards, Navigation components
Design Tokens - single source of truth for style values
Guidelines & Principles - rules for how UI should look and behave
Documentation
Pros and Cons Of SSR?
SSR = Server-Side Rendering
SSR improves SEO by allowing web crawlers to see the fully rendered page.
SSR generally doesn't impact static websites as they do not rely heavily on rendering processes that benefit from server-side rendering.
SSR can actually increase the TFB (Time To First Byte) as we need to first render the application on the server and then send the rendered response.
Tag(s): Frontend optimization.
Accessibility
What are Semantic HTML tags?
These are tags that define the meaning of the content they contain.
They make HTML more understandable for both humans and machines, including search engines and accessibility tools.
These are some of the roughly 100 semantic elements available.
Examples:
<header>
: Defines the header of a document or a section. <h1>
: Defines a top title <nav>
: Defines a section of navigation links. <main>
: Defines the main content of a document. <article>
: Defines a self-contained piece of content that can be distributed or reused independently. <aside>
: Defines content that is tangentially related to the surrounding content, like a sidebar. <footer>
: Defines the footer of a document or a section. <section>
: Defines a generic section of a document. <figure>
: Defines self-contained content like images, diagrams, or code listings.
https://developer.mozilla.org/en-US/docs/Glossary/Semantics
https://web.dev/learn/html/semantic-html/
What's ARIA?
ARIA stands for Accessible Rich Internet Applications.
ARIA roles provide semantic meaning to elements on a webpage, enabling assistive technologies to better understand and interact with the content.
If Semantic HTML tags isn’t possible or relevant enough, utilize the 'role' attribute and ARIA labels to define the purpose and function of elements.
So either:
Non-Semantic HTML with 'role' attribute and ARIA label. i.e.
<div role="application">
Semantic HTML with 'role' attribute and ARIA label. i.e.
<section role="banner">
https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Roles
https://web.dev/learn/accessibility/aria-html
https://wpshout.com/wai-aria-roles/
https://stackoverflow.com/questions/4509761/whats-the-best-semantic-way-to-wrap-a-search-area
Do you know some tools for Accessibility?
axe DevTools - Web Accessibility Testing
A11y ESLint plugin - static evaluation of the JSX to spot accessibility issues in React apps
What are the Best Practices for Accessibility?
Use Semantic HTML.
Use role
attribute (ARIA) when needed.
Use appropriate contrast for text to ensure readability.
Use the tabindex
HTML attribute to control the focus order.
Use dev tools to test the quality of the accessibility of your page.
Use A11 to check you have the right accessibility for your target audience https://www.a11yproject.com/checklist/
when should you use HTML ARIA attributes?
Whenever we cannot use semantic HTML tags.
Semantic HTML elements (such as
,, , etc.) provide built-in accessibility features by conveying the meaning and structure of the content to both users and assistive technologies(like screen readers).
However, in cases where semantic HTML alone cannot adequately describe the interactive or dynamic nature of certain elements (such as custom widgets or dynamic content), ARIA attributes should be used to supplement accessibility.
Examples of poor accessibility?
Poor contrast between text and background - this directly impacts accessibility, as it can make content difficult or impossible to read for users with visual impairments
Using images of text instead of actual text - screen readers cannot interpret text within images. Users who rely on screen readers or have visual impairments will not be able to access the information conveyed in the images, resulting in a loss of content and functionality.
Incorrect Answers:
Including decorative images with empty alt attributes - Decorative images do not need an alt attribute because they do not convey any meaningful information to users.
Not optimizing images for fast loading times(with lazy loading) - this might improve the performance of the page, but it does not impact accessibility.
How do we solve accessibility issues as part of our development code quality process?
Running Accessibility audits with tools like Lighthouse or the axe DevTools
Setting up the a11y linter to catch accessibility issues in the IDE (HTML, JSX, etc)
Security and Attacks
What is the most effective method to prevent Cross-Site Scripting (XSS) attacks in a frontend application?
Validating and sanitizing all user input before rendering it on the webpage
To prevent XSS Attacks for accessing sensitive data from our cookies we should?
Set cookies as HttpOnly.
When cookies are used in web applications, they are automatically included in every request sent to the server. By setting a cookie with the HttpOnly attribute, you ensure that the cookie cannot be accessed by JavaScript running in the browser. This restriction is crucial because it prevents malicious scripts injected into your web pages from accessing the cookie's contents.
This security feature is essential in scenarios where an attacker might exploit XSS vulnerabilities to execute unauthorized scripts in a user's browser. Such scripts could attempt to steal cookie data, including potentially sensitive session tokens. With HttpOnly enabled, even if an attacker succeeds in injecting malicious script, the script would not be able to read the cookie, reducing the risk of session hijacking.
To prevent Man In The Middle Attacks from accessing sensitive data from cookies we should write the cookies with the following property:
Secure - when set, ensures that cookies are sent only over HTTPS, protecting them from interception via man-in-the-middle attacks on insecure networks.
Which HTTP header is important for preventing clickjacking attacks?
X-Frame-Options.
X-Frame-Options, when set to DENY or SAMEORIGIN, prevents the webpage from being displayed in a frame, which is a common technique used in clickjacking attacks.
What's Clickjacking?
TLDR: hidden malicious iframe.
Imagine an attacker who builds a web site that has a button on it that says “click here for a free iPod”. However, on top of that web page, the attacker has loaded an iframe with your email account, and lined up exactly the “delete all messages” button directly on top of the “free iPod” button. The victim tries to click on the “free iPod” button but instead actually clicked on the invisible “delete all messages” button. In essence, the attacker has “hijacked” the user’s click, hence the name “Clickjacking”.
What is the most effective method to prevent Cross-Site Scripting (XSS) attacks in a frontend application?
Validating and sanitizing all user input before rendering it on the webpage.
Avoid rendering user inputs or scripts directly in the application — in React do not use __dangerouslySetInnerHtml and avoid setting innerHTML in general
XSS Attacks(Cross-Site Scripting) happens when the attacker:
Can persist JavaScript code in our system
Our users load and execute that code on their web browsers
To prevent XSS Attacks for accessing sensitive data from our cookies we should?
Set cookies as HttpOnly
To prevent Man In The Middle Attacks from accessing sensitive data from cookies we should write the cookies with the following property:
secure
Which HTTP header is important for preventing clickjacking attacks?
X-Frame-Options
Web Performance, Core Web Vitals, Optimization
What are the steps to build a high performance web app?
Diagnosis - Lighthouse
Server Optimization - compression, caching
Static Asset Optimization - css, js, images, fonts
JavaScript Optimization - code splitting, lazy loading, dynamic imports
Framework Optimization - react memo, decrease re-renderings
In all of the points above: implement best practices and remove anti-patterns that crept in.
What's Client Caching?
Client Caching = Browser Caching = HTTP Caching.
Reduces files sent by server - by allowing users to store assets like images, JavaScript files, and CSS files on their computer.
Indicates what file(s) should be cached by the browser and reused in the following requests (using HTTP headers), unless a new version is released.
What can you do to optimize images?
Third-party Compression Tools: Before even beginning with webpack, consider using tools like TinyPNG or JPEGmini to compress your images. It ensures your starting point already involves optimized assets.
Lazy Loading: Always remember to incorporate lazy loading for images. Utilize the loading=“lazy” attribute on image tags. This ensures images load only when in the viewport, enhancing the initial page load time.
Content Delivery Network (CDN): If your React application is expected to have a wide user base, consider serving your images via a CDN. CDNs cache content across global servers, ensuring faster delivery times.
Responsive Images with srcSet: In today’s age of multiple devices, it’s crucial to serve the right image size to the right device. Use the srcSet attribute to handle this efficiently.
Optimize images using your build/bundling tool
How do you optimize images using webpack?
There are various plugins available such as:
image-webpack-loader
compression-webpack-plugin
ImageMinimizerWebpackPlugin
https://cloudinary.com/blog/guest_post/optimize-images-using-webpack-in-react
https://www.npmjs.com/package/compression-webpack-plugin
https://webpack.js.org/plugins/image-minimizer-webpack-plugin/
What's code splitting?
Code splitting is a technique used in web development to break down a large JavaScript codebase into smaller, more manageable chunks that can be loaded independently.
This allows browsers to download only the necessary code for the current page or functionality, improving initial load time and overall performance.
This is done by the bundler, i.e. webpack or vite
Tag(s): Frontend optimization, Javascript optimization.
https://webpack.js.org/guides/code-splitting/
What's Cache Busting? And which method is used in production environments to implement cache busting?
Cache Busting ensures that users always load the most recent version of a resource like CSS or JavaScript files.
It is done in production by appending a unique hash based on the file's content to the filename.
This is often done by the bundler, i.e. webpack or vite
https://webpack.js.org/guides/caching/
How do you optimize the JavaScript Bundle ?
JavaScript Bundle Optimization can be done with:
Bundle Cleanup
: Analyze your bundle and reduce your JavaScript bundle size by removing unused code, uninstalling unused packages, or replacing them with vanilla js implementation.Minification and uglification
: to reduce the size of the final javascript file.Code Splitting
: Implement code splitting and defer non-critical JavaScript to ensure that only necessary scripts are loaded initially for each page, improving SPA performance. Module bundlers will tag the non-critical scripts with defer or async so the browser will download them in parallel and parse and execute them after the first render.
What are the most common ways to compress JavaScript for the web browser?
Gzip
and Brotli
.
Brotli has better compression ratio at similar compression levels.
https://www.patterns.dev/vanilla/compression/
From a web performance perspective, which image format is generally considered the best (high compression rates that still maintain good image quality)?
WebP
If you want to display different images depending on the viewport size to enhance responsiveness and optimize loading times, which HTML attribute should you use?
The srcset
attribute with the <img>
tag.
This attribute allows you to define multiple source images along with their dimensions, enabling the browser to choose the most appropriate image based on the screen resolution and device orientation.
Tag(s): Frontend optimization, Image optimization.
What's Critical CSS?
Critical CSS, aka Critical Path CSS, aka Above the fold CSS.
It is the CSS applied to above-the-fold elements.
It is the CSS responsible for content a viewer sees on page load, before scrolling.
The PM complained the web app is slow which frustrates users. What is the first step to fix it?
Use:
Dev tools to run a
Core Web Vitals
analysis to understand where the perception of slow comes from - i.e. with Lighthouse (built-in with Google Chrome Dev Tools) or CatchPointProduction Monitoring
:Real User Monitoring
(RUM) tools such asSentry
for gathering real-world user data is essential -Chrome Performance Insights
(Chrome Dev Tool)Performance Tab
in Chrome Dev Tools
https://github.com/GoogleChrome/lighthouse
https://web.dev/articles/optimize-vitals-lighthouse
https://www.catchpoint.com/webpagetest
https://sentry.io/
https://www.speedcurve.com/
Any tips when using Lighthouse ?
Open an incognito window in Chrome when running Lighthouse - this removes Chrome addons and their heavy JavaScript
Click "Expand View"
Click "Expand View", then "Treemap" - see treemap of all the JavaScript sent to our web browser
Click "Try Insights"
https://github.com/GoogleChrome/lighthouse
https://web.dev/articles/optimize-vitals-lighthouse
What are the 3 Pillars Of Web Performance?
Perceived Load Speed
ResponsivenessToInput/Interactivity
Visual Stability
What's the difference between Core Web Vitals and the 3 Pillars Of Web Performance?
Core Web Vitals are a set of metrics that measure key aspects of a webpage's user experience, specifically focusing on : loading speed, interactivity, and visual stability.
Same focus as 3 Pillars Of Web Performance. But different namings:
Largest Contentful Paint (LCP): Perceived Load Speed: how long it takes for the largest content element on a page to become visible. A good LCP score should be less than 2.5 seconds.
Interaction to Next Paint (INP): Responsiveness/Interactivity: how quickly a website responds to user interactions. A good INP score should be 200 milliseconds or less.
2.B. First Input Delay (FIP): Responsiveness/Interactivity: how long it takes for the first text/image on a page to become visible. Being deprecated, and replaced by INP.
Cumulative Layout Shift (CLS): Visual Stability: the amount of unexpected visual shifting during page loading. A good CLS score should be less than 0.1.
There are additional Core Web Vitals:
FCP for First Contentful Paint: time at which the first text or image is painted.
How can you improve a bad CLS (Cumulative Layout Shift)?
By adding a visual placeholder library i.e. skeleton, shimmer
Tag(s): Frontend optimization.
https://shimmereffectreact.vercel.app/
https://github.com/tomzaku/react-native-shimmer-placeholder
Which web performance metric will improve the most if we add a CDN to our architecture?
FCP (First Contentful Paint) - the time it takes to render the first text, image, non-white canvas, or non-white SVG.
Adding a CDN will most likely:
Decrease the download time of the assets(because the assets are geographically distributed which reduces the network latency) Decrease the size of the assets(compression, content negotiation) Apply the right http caching headers
What's the Critical Rendering Path?
The Critical Rendering Path (CRP) is composed of several key steps for processing and displaying a web page:
HTML Request (fetch)
Parse HTML, Build DOM (render)
Blocking Resources in Head - fetch and process
a. CSS Fetch and Process
b. JavaScript Processing
Render
a. Render Tree Construction (CSSOM and DOM trees)
b. Layout Calculation (Positions and Sizes for Elements)
c. Paint
d. Font and Images are loaded
What are Critical Tasks that block the First Render?
The following tasks will block the first render and result in a low FCP score:
CSS Download and Processing
Synchronous JavaScript Execution
HTML Parsing Pauses
Server-Side rendering (SSR) would have the most positive impact on the following web performance metric:
FCP (First Contentful Paint) - the time it takes to render the first text, image, non-white canvas, or non-white SVG.
Rendering the application on the server will decrease the time we need to show something to the users because it speeds up the rendering (as the client receives pre-rendered html instead of JS).
Server Side Rendering prevents the White Screen of Death (WSD), which is a common issue with client side rendering.
Tag(s): Frontend optimization.
https://web.dev/articles/rendering-on-the-web
What's the performance metric Time To First Byte (TTFB) ?
Measures how long it takes for a web server to respond to a request and send the first byte of data back to the client.
It's a key indicator of server responsiveness and network performance.
TTFB is measured from when a browser sends a request to when it receives the initial byte of the response.
Tag(s): Frontend optimization.
What's the performance metric First Contentful Paint (FCP) ?
Measures the time it takes for any part of a page's content to be rendered on the screen after the user navigates to it.
This includes text, images, background images, elements, and non-white elements.
FCP is a key metric for understanding perceived page load speed and user experience.
Tag(s): Frontend optimization.
What's the performance metric Cumulative Layout Shift (CLS) ?
Calculates the shifting of elements while the page is being downloaded and rendered.
The more common occurrences are on images, buttons and other interactive elements but can be easily spotted on text as well.
Tag(s): Frontend optimization.
What's the performance metric Interaction to Next Paint (INP) ?
Measures user interface responsiveness – how quickly a website responds to user interactions like clicks or key presses.
Tag(s): Frontend optimization.
First Input Delay (FID) - performance metric
Measures the responsiveness of a webpage by tracking the time it takes for a browser to respond to a user's first interaction, i.e. click a link or tap a button.
It essentially indicates how quickly the browser becomes able to process a user's interaction after it's initiated.
FID was previously a Core Web Vitals metric, but has been replaced by Interaction to Next Paint (INP).
Tag(s): Frontend optimization.
Which performance metric is most directly affected by excessive re-renders in web frameworks such as React, Vue, or Angular?
INP (Interaction to Next Paint) - the time it takes to paint the next frame after a user interaction.
First Input Delay (FID) measures the time from when a user first interacts with a page (i.e., when they click a link
Interaction to Next Paint (INP): measures the responsiveness of an application by tracking the time from when a user interacts with the page to when the browser is able to update the visual display in response to that interaction.
First Input Delay (FID): measures the time from when a user first interacts with a page (i.e., when they click a link, tap on a button, or use a custom, interactive control) to the time when the browser is actually able to begin processing event handlers in response to that interaction.
Excessive re-renders can significantly delay both metrix as they often involve additional computations and DOM manipulations, which block the main thread. This leads to longer wait times for visual updates after interactions, such as clicks or key presses, directly impacting the user's perceived responsiveness of the application.
Tag(s): Frontend optimization.
Module Bundlers
What are Module Bundlers?
Module Bundlers combine several javascript files(modules) into a single one(the bundle) to be shipped to the browser.
They usually rely on an internal structure built from the import statements in your code called the dependency graph.
Module Bundlers can also ingest formats like CSS, SASS, and JPEG and apply web performance transformations like code minification, and compression to the bundle.
What's a Dependency Graph?
An internal tree-like structure created by module bundlers based on imports and exports in your code.
What are Polyfills?
A piece of code that replaces a missing language feature in browsers that do not support it yet, for example, object deconstruction in Internet Explorer.
What's Tree Shaking?
Only possible when using ES Static imports (vs Common JS imports).
Removal of dead code (unused code) by the module bundler for a smaller final bundle and better performance.
What are Source Maps?
Transforms the code that runs in the browser to the original source which makes it easier to debug.
What's cache busting?
a technique used in web development to ensure users always see the latest version of website resources (like CSS and JavaScript files) by preventing the browser from using cached, potentially outdated versions.
It works by appending a unique identifier, such as a version number or timestamp, to the file's URL, causing the browser to treat it as a new file and download it from the server, bypassing the cache.
Often by appending a hash to file names.
What's Treeshaking?
The process through which the module bundler removes unused dependencies (dead code).
How can we debug in production after the code was compressed, uglified and minified ?
We must emit Source Maps from our build process.
In our Webpack setup, we use TypeScript with the TypeScript loader to transpile our code and ES6 import/export for our modules. However, we noticed that tree shaking did not work(when building for production), and we are still shipping unused modules in the final bundle. What could be the reason for this issue?
TLDR: TypeScript output is set to compile to ES5 or earlier, using CommonJS modules which do not support tree shaking.
ES6 modules (import/export syntax) are necessary for tree shaking to work effectively because they support static analysis, whereas CommonJS modules (require/module.exports) do not. If TypeScript transpiles code to use CommonJS modules, Webpack will not be able to perform tree shaking, resulting in unused code being included in the production bundle.
Ensuring that the TypeScript compiler (tsconfig.json) is set to output ES6 modules (by setting "module": "es6" or "module": "esnext") will solve the issue.
The other options are wrong for different reasons:
Side Effects: An incorrect configuration of the sideEffects property can indeed affect tree shaking by causing Webpack to include modules that it otherwise might exclude, this is more about optimizing an already functional tree shaking setup rather than the primary cause of tree shaking failing entirely. If tree shaking isn't working at all, the issue is more likely related to how the modules are handled, as in using CommonJS instead of ES6 modules.
Webpack Mode: Setting the Webpack mode to development indeed disables or reduces optimization processes, including tree shaking. However, the question implies the inspection of a production build, where the production mode should be used.
Polyfills: Incorrect handling of polyfills can increase the bundle size but isn't directly related to tree shaking of your own code modules. Polyfills typically affect how modern JavaScript features are supported in older browsers and are managed through Babel rather than impacting Webpack's tree shaking directly.
Misc
Composition Over Inheritance is an OOP principle that states …
… that we can achieve new functionality by grouping components(or functions) into higher order components in higher order structures
What is the default behavior of a click on the submit button of a <form/>
in the web browser?
<form/>
in the web browser?A GET request on the form url with the form content in the body and a page refresh.
The form data will be submitted to the current URL. This is because when the action attribute is omitted, the browser defaults to submitting the form back to the URL of the page the form is on.
The default HTTP method for form submission is GET. Therefore, the form data will be appended to the URL as encoded query parameters.
After the submission, the browser will refresh the page with the form data visible in the address bar.
In which order will the event handlers be called when the user clicks the button?
most inner button has:
addEventListener("click", onButtonClick)
inner div has:
addEventListener("click", onContainerClick, {capture: true})
outer div has:
addEventListener("click", onOuterContainerClick)
The correct answer is Capturing & Bubbling: onButtonClick() > onOuterContainerClick() > onContainerClick().
Here's the sequence of events when the "Submit" button is clicked:
onContainerClick() — Because the {capture: true} option is used, this event handler is set to execute during the capturing phase, which occurs before the target phase (where the event occurs on the element that was actually clicked).
onButtonClick() — This occurs at the target phase, specifically on the button element where the click event actually happened.
onOuterContainerClick() — This event handler is not specified to execute during the capturing phase (the default is bubbling), so it will execute last, during the bubbling phase after the event has reached the outer_container in the propagation sequence.
The capturing phase occurs from the outermost element down to the target element, and the bubbling phase occurs from the target element up to the outermost element. Since the onContainerClick is explicitly set to capture, it goes first, followed by the button's click handler as the event target, and finally, the event bubbles up to the outer_container.
Which GIT flow would you recommend when starting a new project with a small team?
Feature branch
What does git squash do?
Combine multiple commits into a single commit
Last updated