HTML Flashcards

1
Q

What are HTML5 structure elements

A
<header> - Used to define header for a document or a section
<nav> - Used to define container for navigation links
<section> - Used to define a section inside a document
<article> - Used to tag an independent self-contained article
<aside> - Defines the content separately (just like a sidebar)
<footer> - Used for tagging a footer inside a document or a section
<details> - Used to define any additional details
<summary> - Used to define a heading inside the <details> element
<main>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the importance of Semantic Markup

A
  1. gives structure
  2. good for SEO
  3. good for accessibility, screen readers
  4. easy to maintain
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are web components

A

Web components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps. You can also create custom versions of standard HTML elements. Some of the elements are

<shadow>, <content>, <element>, <template>, <slot>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the 7 layers in OSI model

A

There are 7 layers in the OSI model:

Physical Layer,
Data Link layer,
Network Layer,
Transport Layer,
Session Layer,
Presentation Layer, and
Application Layer.

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

async vs defer on script tag

A

async Attribute

*	Functionality: When you add the async attribute to a <script> tag, the script is loaded asynchronously with the rest of the page. This means that the script is downloaded in the background and will execute as soon as it is downloaded, without waiting for the rest of the page to load.
*	Use Case: async is useful for scripts that do not depend on other scripts and do not modify the DOM (Document Object Model). It ensures that the script does not block page rendering while it is loading.

defer Attribute

*	Functionality: The defer attribute, when used, also allows the script to load asynchronously, but it defers the execution of the script until the entire HTML document has been parsed. This means the script execution waits until the HTML parsing is complete but does not block the HTML parsing itself.
*	Use Case: defer is ideal for scripts that need to access or modify the DOM or when your scripts rely on other scripts that are also deferred. It ensures that the script will only run after the HTML document is fully parsed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is accessibility

A

As the browser parses the content received, it builds the document object model (DOM) and the CSS object model (CSSOM). It then also builds an accessibility tree. Assistive devices, such as screen readers, use the AOM to parse and interpret content. The DOM is a tree of all the nodes in the document. The AOM is like a semantic version of the DOM.

AOM nodes have name, description, role, state

landmark roles - major content areas like banner(header), main, navigation
structure roles - structural information tooltip, list, table
widget roles - interactive elements (tab, button, searchbox)
window roles - dialog, alertdialog
live region role - timer, log, alert (useful for content that is changing like chatbox)

aria-role
aria-live - off, polite, assertive
aria-label - label not visible on UI
aria-labelledby - id of the element that describes it
aria-description
aria-describedby
aria-controls
aria-selected

Browser compatibility
css accessibility - use contrast, legible fonts, mobile support
internationalization i18n

Ensuring the accessibility of a web application is essential for creating inclusive and user-friendly experiences for all users, including those with disabilities. Here are key aspects and best practices to consider:

Key Aspects of Web Accessibility

1.	Perceivable: Information and user interface components must be presented in ways that users can perceive. This includes providing text alternatives for non-text content, such as images (<alt> attributes), ensuring content is adaptable to different screen sizes, and using sufficient color contrast.
2.	Operable: User interface components and navigation must be operable. This includes making all functionality available from a keyboard, giving users enough time to read and use content, and not designing content in a way that is known to cause seizures.
3.	Understandable: Information and the operation of the user interface must be understandable. This involves making text readable and understandable, ensuring web pages operate in predictable ways, and helping users avoid and correct mistakes.
4.	Robust: Content must be robust enough to be interpreted reliably by a wide variety of user agents, including assistive technologies. This includes ensuring compatibility with current and future user tools.

Best Practices for Web Accessibility

1.	Use Semantic HTML: Use HTML elements according to their purpose (e.g., <header>, <footer>, <article>, <nav>). This helps screen readers and other assistive technologies understand the structure and navigate the content efficiently.
2.	Keyboard Navigation: Ensure that all interactive elements (buttons, links, forms) are reachable and operable via keyboard. Use the tabindex attribute wisely to manage focus order.
3.	Aria Landmarks and Roles: Use ARIA (Accessible Rich Internet Applications) landmarks and roles to define regions of the page (e.g., <main>, <aside>, <nav>). This helps users with screen readers navigate the content.
4.	Provide Text Alternatives: Include text alternatives for all non-text content. This means using alt attributes for images, captions for videos, and transcripts for audio content.
5.	Color Contrast: Ensure that text has sufficient contrast against its background. The Web Content Accessibility Guidelines (WCAG) recommend a contrast ratio of at least 4.5:1 for normal text and 3:1 for large text.
6.	Responsive Design: Ensure that your website is responsive and works well on various devices and screen sizes. This improves accessibility for users who rely on different devices.
7.	Forms Accessibility: Make sure forms are accessible by associating labels with inputs using the for attribute and providing clear instructions and error messages.
8.	Skip Navigation: Provide a way for users to skip repetitive content. A common method is a “Skip to main content” link at the top of the page.

Tools and Resources

1.	Accessibility Checker Tools:
*	WAVE: Web Accessibility Evaluation Tool.
*	Axe: Accessibility testing tool for websites and applications.
*	Lighthouse: Built into Chrome DevTools for checking various aspects of web performance and accessibility.
2.	Guidelines and Standards:
*	WCAG (Web Content Accessibility Guidelines): The main international standard for web accessibility. Following WCAG helps make content accessible to a wider range of people with disabilities, including blindness and low vision, deafness and hearing loss, learning disabilities, cognitive limitations, limited movement, speech disabilities, and combinations of these.
*	ARIA (Accessible Rich Internet Applications): Provides a way to make web content and web applications more accessible to people with disabilities.

Web accessibility levels are defined by the Web Content Accessibility Guidelines (WCAG), which are a set of recommendations for making web content more accessible. The guidelines are organized into three levels of conformance: A, AA, and AAA. Each level builds upon the previous one, with Level A being the most basic and Level AAA being the most comprehensive.

WCAG Levels Explained

1.	Level A (Minimum Accessibility):
*	Focus: Basic web accessibility that ensures no content is completely inaccessible.
*	Requirements: Addresses the most critical accessibility barriers that prevent users from using the content altogether.
*	Examples:
*	Text alternatives for non-text content (e.g., alt attributes for images).
*	Keyboard accessibility for all content.
*	Avoidance of content that can cause seizures (e.g., avoiding flashing content).
2.	Level AA (Mid-Range Accessibility):
*	Focus: Deals with the biggest and most common barriers for disabled users.
*	Requirements: Aims to make web content accessible to a broader range of people with disabilities.
*	Examples:
*	Sufficient color contrast between text and its background.
*	Text resizing without loss of content or functionality.
*	Navigation and focus order consistency.
*	Provision of multiple ways to locate a web page within a set of web pages.
3.	Level AAA (High-Level Accessibility):
*	Focus: The highest and most complex level of web accessibility.
*	Requirements: Ensures the highest level of accessibility, addressing the needs of the widest range of disabilities.
*	Examples:
*	Extended requirements for contrast and text spacing.
*	Comprehensive support for sign language interpretation for all pre-recorded audio content.
*	Enhanced navigability and readability of content.
*	Provision of detailed help and instructions.

Practical Applications

*	Level A: Ensures no barriers prevent users from accessing content. Implementing Level A guidelines is a basic requirement for making web content accessible.
*	Level AA: Addresses the most common barriers and is typically the level of conformance aimed for by most organizations, as it ensures a high level of accessibility for a majority of users.
*	Level AAA: Suitable for organizations that want to go above and beyond the basic and common barriers, providing the highest accessibility level. Achieving AAA is challenging and not always feasible for all types of content.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

HTML Table

A
<table>
  <caption>MLW Alumni</caption>
  <thead>
    <tr>
      <th>Name</th>
      <th>Destiny</th>
      <th>Year</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>Hal Gibrah</th>
      <td>Calculator</td>
      <td>2020</td>
    </tr>
    <tr>
      <th>Cathy Terr</th>
      <td>Waste disposal</td>
      <td>2018</td>
    </tr>
    <tr>
      <th>Lou Minious</th>
      <td>Lightbulb</td>
      <td>1956</td>
    </tr>
  </tbody>
</table>

attributes
rowspan for tr, colspan for td or th

for styling
~~~

<colgroup>
<col></col>
</colgroup>

~~~

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

Custom attributes

A

use data-<name> to create custom attributes.</name>

Get the value using el.getAttribute('data-name'); or el.dataset[name]

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

tabindex values

A

Using tabindex

1.	Positive Values: Setting tabindex to a positive number (e.g., tabindex="1") places the element in the sequential keyboard navigation order, with the order defined by the value of tabindex. Lower numbers are focused first. This can be useful for creating a specific flow of navigation different from the source order in the HTML, but it should be used sparingly as it can make navigation confusing if overused or used inconsistently.
2.	tabindex="0": Adding tabindex="0" to an element makes it reachable via sequential keyboard navigation, using its position in the document structure to determine its order. This is useful for elements that are not focusable by default (like divs and spans) but need to be interactive.
3.	Negative Values (tabindex="-1"): Elements with tabindex="-1" are not reachable via the keyboard, but they can be focused programmatically (using JavaScript). This is useful for elements that you might want to focus dynamically without affecting the natural tabbing order of the page.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Meta tags

A
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>My First Webpage</title>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta name="author" content="FrontendExpert" />
		<meta name="description" content="value"/>
    <base href="https://algoexpert.io" />
  </head>
  <body>
    <p>
      This link is relative to the base:
      <a href="/frontend" target="_blank">Frontend Expert</a>!
    </p>
  </body>
</html>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Script type=”module” features

A

Key Features of type=”module”

1.	Scoped Variables: Variables declared in a module are scoped to that module and not global.
*	This helps in avoiding conflicts with other scripts.
2.	Imports and Exports:
*	Modules can import and export functionality between different JavaScript files.
Deferred Execution:
*	Scripts with type="module" are deferred automatically, which means they will not block the HTML parsing.
*	They execute in the order they are encountered.
4.	Strict Mode:
*	JavaScript modules always run in strict mode, regardless of whether "use strict" is declared.
*	This means certain actions that are considered bad practices, like using undeclared variables, will throw errors.
5.	Top-Level this is undefined:
*	In a module, the top-level this is undefined, which is different from scripts where this refers to the global object.
6.	Dynamic Imports:
*	Modules support dynamic import syntax, which allows for loading modules on-demand.
// module.js
export function greet() {
  console.log('Hello, world!');
}

// main.js
import { greet } from './module.js';
greet(); // Outputs: Hello, world!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Form

A
<form id="registrationForm" action="/submit" method="post">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required minlength="3" maxlength="15">
    <br><br>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>
    <br><br>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required minlength="6">
    <br><br>

    <label for="age">Age:</label>
    <input type="number" id="age" name="age" required min="18" max="99">
    <br><br>

    <input type="submit" value="Register">
  </form>

  <script>
    document.getElementById('registrationForm').addEventListener('submit', function(event) {
      if (!this.checkValidity()) {
        event.preventDefault();
        alert('Please fill out the form correctly.');
      }
    });
  </script>

HTML5 offers built-in validation attributes that are easy to use and require minimal effort:

1.	required: Ensures the field is not empty.
2.	type: Defines the type of data expected, such as email, url, number, date, etc.
3.	min and max: Sets minimum and maximum values for numeric and date inputs.
4.	pattern: Specifies a regular expression that the input must match.
5.	maxlength and minlength: Specifies the maximum and minimum number of characters allowed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

http caching

A
  1. use Cache-Control headers in response from server to cache the api response at browser
  2. use Etags
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

file/folder viewer js

A

https://jsfiddle.net/harshdand/ztyd1oa7/108/

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

Internationalization

A

Internationalization (i18n) and localization (l10n) are processes to ensure that web applications can support multiple languages and regions. Here is a basic approach to implement internationalization and localization in an HTML and JavaScript-based web application

 <h1 data-i18n="greeting"></h1>
 <p data-i18n="farewell"></p>

 <button onclick="setLanguage('en')">English</button>
 <button onclick="setLanguage('es')">Español</button>
const translations = {
  en: {
    'greeting': 'greeting'
  },
  es: {
    'greeting': 'dasdfasd'
  }
};

function setLanguage(lang) {
  if (translations[lang]) {
    applyTranslation(lang);
  }
}

function applyTranslation(lang) {
  document.querySelectorAll('[data-i18n]').forEach(element => {
    const key = element.getAttribute('data-i18n');
    element.textContent = translations[lang][key];
  });
}

document.addEventListener('DOMContentLoaded', () => {
	console.log(navigator.language);
  const userLang = navigator.language.startsWith('es') ? 'es' : 'en'; // Example language detection
  setLanguage(userLang);
});

or use i18next

<h1 id="greeting"></h1>
<p id="farewell"></p>

<select id="language-switcher">
  <option value="en">English</option>
  <option value="es">Español</option>
</select>

  document.addEventListener('DOMContentLoaded', () => {
    i18next.init({
      lng: 'en', // default language
      resources: {
        en: {
          translation: {
            "greeting": "Hello",
            "farewell": "Goodbye"
          }
        },
        es: {
          translation: {
            "greeting": "Hola",
            "farewell": "Adiós"
          }
        }
      }
    }, (err, t) => {
      if (err) return console.error(err);

      updateContent();
    });

    function updateContent() {
      document.getElementById('greeting').innerHTML = i18next.t('greeting');
      document.getElementById('farewell').innerHTML = i18next.t('farewell');
    }

    document.getElementById('language-switcher').addEventListener('change', (event) => {
      i18next.changeLanguage(event.target.value, updateContent);
    });
  });
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Internationalization

A
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import HttpBackend from 'i18next-http-backend';

i18n
  .use(HttpBackend)
  .use(initReactI18next)
  .init({
    fallbackLng: 'en',
    lng: 'en',
    backend: {
      loadPath: '/locales/{{lng}}.json', // Path to your translation files
    },
    interpolation: {
      escapeValue: false, // React already does escaping
    }
  });

export default i18n;

<br></br>

// usage in component
import React from 'react';
import { useTranslation } from 'react-i18next';

function App() {
  const { t, i18n } = useTranslation();

  const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
  };

  return (
    <div className="App">
      <h1>{t('greeting')}</h1>
      <p>{t('farewell')}</p>
      <button onClick={() => changeLanguage('en')}>English</button>
      <button onClick={() => changeLanguage('es')}>Español</button>
    </div>
  );
}

export default App;
17
Q

Programmatic identification of impact areas of code to reduce bugs and importance of test

A

Static Code Analysis
Static code analysis tools scan the source code without executing it to find potential bugs, code smells, and areas of improvement. Examples include:

ESLint for JavaScript
SonarQube for multiple languages

Code Coverage Tools
Unit testing in CI environment
npm audit

18
Q

Understanding of the non functional aspects of code. i.e scalability, modularity and performance

A

Scalability
Definition: Scalability refers to the ability of an application to handle growth, whether in terms of user load, data volume, or feature complexity, without performance degradation.
Practices:
Code Splitting: Divide code into chunks that can be loaded on demand, improving load time.
Lazy Loading: Load components only when they are needed.
Efficient State Management: Use state management libraries (like Redux) wisely to avoid unnecessary re-renders.
Responsive Design: Ensure the application works well on various devices and screen sizes.

Modularity
Definition: Modularity involves designing the application in separate, self-contained units (modules) that can be developed, tested, and maintained independently.
Practices:
Component-Based Architecture: Use frameworks like React to build UI components that encapsulate functionality and styling.
Reusability: Create reusable components to avoid code duplication.
Separation of Concerns: Split code into logical sections (e.g., separating UI logic from business logic).
Use of Modules: Use ES6 modules or similar to organize code into discrete files and directories.
Performance
Definition: Performance pertains to how quickly and efficiently an application responds to user interactions and loads resources.

Practices:
Optimizing Assets: Minimize and compress CSS, JavaScript, and images.
Code Minification: Reduce the size of JavaScript files through minification.
Caching: Implement browser caching and service workers to cache resources.
Reducing HTTP Requests: Combine files and use sprite sheets to minimize the number of HTTP requests.
Efficient Rendering: Optimize rendering performance by avoiding unnecessary DOM manipulations and using virtualization for large lists.

Server-Side Rendering (SSR)

  • Implement SSR: Use frameworks like Next.js for better performance and SEO.

API Optimization

  • GraphQL or REST: Choose the right API paradigm.
  • Data Caching: Implement caching strategies like Redis or in-memory caches.
  • Load Balancing: Distribute traffic across multiple servers.

Static Site Generation (SSG)

  • Use SSG for Static Pages: Pre-generate pages at build time (Next.js example).
  1. Infrastructure

Content Delivery Network (CDN)

  • Use a CDN: Serve static assets from locations closer to users.

Load Balancing

  • Distribute Traffic: Use load balancers to distribute incoming traffic across multiple servers.

Auto-Scaling

  • Scale Automatically: Use cloud providers’ auto-scaling features to handle traffic spikes.
  1. Monitoring and Analytics

Performance Monitoring

  • Use Tools: Implement monitoring tools like New Relic, Datadog, or Google Analytics.

Logging

  • Centralized Logging: Aggregate logs for easy analysis and troubleshooting.
19
Q

Testing types

A
  1. Test-Driven Development (TDD)
    Description: TDD is a development process where tests are written before writing the code that needs to be tested. It follows a cycle of writing a test, making it pass, and then refactoring.

Advantages:

Improved Code Quality: Encourages writing clean, well-designed code.
Less Debugging: Since tests are written first, many bugs are caught early in the development process.
Documentation: Tests serve as documentation for how the code is supposed to work.
Refactoring Confidence: Makes refactoring safer and easier, as existing tests will catch any issues.
2. Behavior-Driven Development (BDD)
Description: BDD is an extension of TDD that focuses on the behavior of an application for its users. It involves writing tests in a natural language that non-technical stakeholders can understand.

Advantages:

Enhanced Communication: Improves collaboration between developers, testers, and non-technical stakeholders.
Clear Requirements: Tests are written in plain English, making it easier to understand requirements.
User-Centric: Ensures the application meets user expectations and requirements.
3. Acceptance Test-Driven Development (ATDD)
Description: ATDD involves writing acceptance tests before development starts, often in collaboration with customers or business analysts.

Advantages:

Customer Involvement: Ensures that the software meets customer requirements.
Early Defect Detection: Identifies issues early in the development process.
Better Understanding: Developers gain a clearer understanding of the desired functionality.
4. Unit Testing
Description: Unit testing involves testing individual units or components of a software application to ensure they work as expected.

Advantages:

Isolation: Tests components in isolation, making it easier to pinpoint issues.
Fast Feedback: Quick to write and run, providing fast feedback.
Documentation: Serves as documentation for the codebase.
5. Integration Testing
Description: Integration testing focuses on testing the interactions between different components or systems to ensure they work together as expected.

Advantages:

Detects Interface Issues: Identifies problems in the interaction between integrated components.
Verifies System Integration: Ensures different parts of the system work together.
6. System Testing
Description: System testing involves testing the entire integrated system to verify that it meets the specified requirements.

Advantages:

End-to-End Testing: Tests the system as a whole, ensuring that it functions correctly from start to finish.
Requirement Verification: Verifies that the system meets all specified requirements.
7. Regression Testing
Description: Regression testing involves re-running tests to ensure that changes or additions to the codebase have not introduced new bugs.

Advantages:

Maintains Stability: Ensures that new changes do not negatively impact existing functionality.
Automatable: Can be automated to run frequently and provide quick feedback.
8. Performance Testing
Description: Performance testing assesses the speed, responsiveness, and stability of a system under various conditions.

Advantages:

Identifies Bottlenecks: Helps find performance issues and bottlenecks.
Ensures Scalability: Verifies that the system can handle expected user loads.
9. Usability Testing
Description: Usability testing evaluates how user-friendly and intuitive a software application is.

Advantages:

Improves User Experience: Ensures that the application is easy to use.
User Feedback: Provides direct feedback from real users.
10. Security Testing
Description: Security testing involves identifying vulnerabilities and weaknesses in a software application to ensure it is secure against attacks.

Advantages:

Protects Data: Ensures that user data is protected.
Compliance: Helps meet security standards and regulations.
Conclusion
Each testing methodology has its own advantages and is suited to different stages of the development process. Combining these methodologies can lead to more robust, maintainable, and user-friendly software.

20
Q

Networking concepts

A

For frontend development, understanding certain networking concepts is crucial for building efficient and secure web applications. Here are some key concepts:

  1. HTTP/HTTPS:
    • HTTP (HyperText Transfer Protocol): The protocol used for transferring web pages on the internet. It’s a request-response protocol between a client and a server.
    • HTTPS (HTTP Secure): The secure version of HTTP, which uses SSL/TLS to encrypt data transferred between the client and server, ensuring data integrity and security.
  2. APIs (Application Programming Interfaces):
    • APIs allow communication between different software systems. Frontend applications often consume APIs to fetch data from servers.
    • RESTful APIs: Representational State Transfer, a common architecture for building scalable web services.
    • GraphQL: A query language for your API, providing a more efficient and powerful alternative to REST.
  3. AJAX (Asynchronous JavaScript and XML):
    • A technique for creating asynchronous web applications. It allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes.
  4. CORS (Cross-Origin Resource Sharing):
    • A security feature implemented in web browsers to prevent web pages from making requests to a different domain than the one that served the web page.
  5. WebSockets:
    • A protocol for full-duplex communication channels over a single TCP connection. Useful for real-time applications like chat apps, live notifications, etc.
  6. CDNs (Content Delivery Networks):
    • A system of distributed servers that deliver web content to a user based on their geographic location, the origin of the webpage, and a content delivery server.
  7. DNS (Domain Name System):
    • Translates human-friendly domain names to IP addresses. Understanding how DNS works can help in troubleshooting issues related to domain name resolution.
  8. Caching:
    • Mechanisms for storing copies of data temporarily to reduce server load, speed up data retrieval, and improve user experience. This includes browser caching, server-side caching, and CDN caching.
  9. Authentication and Authorization:
    • Authentication: Verifying the identity of a user or system (e.g., using JWT tokens, OAuth).
    • Authorization: Determining what an authenticated user is allowed to do (e.g., role-based access control).
  10. CSRF and XSS:
    • CSRF (Cross-Site Request Forgery): An attack that forces a user to execute unwanted actions on a web application in which they’re authenticated.
    • XSS (Cross-Site Scripting): An attack where malicious scripts are injected into otherwise benign and trusted websites.

Understanding these concepts will help you build secure, efficient, and responsive frontend applications.