web development - web components

0.0(0)
studied byStudied by 1 person
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/73

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

74 Terms

1
New cards

template

Defined by _________ to provide inert HTML: in a DOM page in a standard way

  • no need to use scri[t to clone the content for later use

2
New cards

shadow

________ DOM:

  • protected subtrees with their own CSS and DOM

3
New cards

Document Object Model

DOM: ___________ ____________ _________
- including HTML, JS

4
New cards

ES6
“type”: “module”

import * as utils

the latest way to import and export

  • using javascript version (___+)

  • if using node.js, need to set ____: ______ in the package.json

  • if i want to import everything, and alias the imported module as utils, use ________ from ….

5
New cards

B

A

event system

web components have 2 forms:

A. single component with attributes and B. multiple components nested


Single component with attributes

<player-card name='Joe' number='21' position='forward'></player-card>

Multiple components instead of attributes using the slotted data instead

<player-card>
   <player-name>Joe</player-name>
   <player-number>21</player-number>
   <player-position>Forward</player-number>
</player-card>

which favors progressive enhancement? __________

which one is simple to implement? __________

what is the popular way to communicate and coordinate within the multiple components system? _______

6
New cards

export
export
./util.js

for example, i want to export the function add and constant PI in the util.js, and import those at app.js

_____ function add() {...}
_____ const PI
import {add, PI} from "_____"

7
New cards

await import("./math.js")

dynamic imports (lazing loading):

when i only need to import at a particular function:

from ./math.js

async function loadMathModule() {
    const math = _______;
    console.log(math.multiply(3, 4)); // 12
}
loadMathModule();

8
New cards

light
shadow
open

Feature

____ DOM

_____ DOM

Global Styling

Yes

No (Scoped)

Encapsulation

No

Yes

JavaScript Access

Yes

Yes when set mode=”___”

Component Isolation

No

Yes

9
New cards

shadow

The ________ DOM is a protected sub-tree where implementation details can be hidden, preventing conflicts with other styles or scripts on a webpage.

10
New cards

Light

In contrast, the _____ DOM is part of the public DOM tree and does not provide encapsulation, making it easier to manipulate but potentially vulnerable to conflicts.

11
New cards

style

script

One advantage of using Shadow DOM is that it helps prevent ______ and ____ conflicts by isolating css and js.

12
New cards

slot

The _______ element in a web component allows content to be passed into the Shadow DOM from the Light DOM while still maintaining encapsulation.

13
New cards

variables

parts

foo::part(my-button) 

<slot name="header"></slot>

<slot name="footer"></slot>

CSS _______ and CSS _____ enable developers to style elements inside the Shadow DOM from the external CSS.

suppose web component named foo like this:

<style>
  .button {
    background-color: blue;
    color: white;
    padding: 10px;
  }
</style>
<button part="my-button" class="button">Click me</button>

how to change the style from external css?

_________{
  background-color: red; /* Override Shadow DOM styling */
}

now suppose i want to render component liek this

<my-component>
  <h1 slot="header">Title Here</h1>
  <p slot="footer">Footer content</p>
</my-component>

how do i construct the HTML in shadow DOM:

____________

14
New cards

security

Using Light DOM may introduce robustness or _______ concerns since there is no encapsulation.

15
New cards

attributes

When using the Shadow DOM, developers can use _______ to pass data into the web component.

16
New cards

shadow host
Shadow Tree
Shadow Boundary

Shadow Root

Light DOM

Flattened Tree

  • _________ : The regular DOM node that the shadow DOM is attached to.

  • _________: The DOM tree inside the shadow DOM.

  • ________: The place where the shadow DOM ends, and the regular DOM begins.

  • _____: The root node of the shadow tree.

  • _________: The DOM that lives outside the shadow DOM.

  • _________: The DOM which you see in DevTools in your browser.

17
New cards

light

shadow-host

light

root

boundary

shadow tree

shadow

flattened tree

<body>

    <h2>This is in the ____ DOM</h2>

    <div id="_____-_____">
        <p>This is inside the ____ DOM (before Shadow DOM is attached).</p>
    </div>

    <script>
        // Select the Shadow Host
        const shadowHost = document.querySelector("#shadow-host");

        // Attach a Shadow ____ (Creates a Shadow ______)
        const shadowRoot = shadowHost.attachShadow({ mode: "open" });

        // Insert Shadow DOM content (____ ___)
        shadowRoot.innerHTML = `
            <style>
                p {
                    color: red;
                    font-weight: bold;
                }
            </style>
            <p>This is inside the _____ DOM</p>
        `;

        // Console log to see the structure
        console.log("Shadow Host:", shadowHost);
        console.log("Shadow Root:", shadowRoot);
        console.log("______ ____ (Rendered View): Open DevTools to see the final rendering.");
    </script>

</body>

18
New cards

super()

this.shadow = this.attachShadow({ mode: 'open' });

this._count = 0;

return [‘count’]

customElements.define('counter-element', CounterElement);

create own wc:

<body>
    <!-- Custom element in action -->
    <counter-element count="5"></counter-element>

    <script>
        class CounterElement extends HTMLElement {
            constructor() {
                _________

                // Attach a shadow DOM
                ____________

                // Create and style the Shadow DOM content
                this.shadow.innerHTML = `
                    <style>
                        .counter {
                            font-family: Arial, sans-serif;
                            font-size: 24px;
                            color: #fff;
                            background: #007bff;
                            padding: 10px 20px;
                            border-radius: 5px;
                            display: inline-block;
                        }
                        button {
                            margin-left: 10px;
                            padding: 5px 10px;
                            font-size: 16px;
                        }
                    </style>
                    <div>
                        <span class="counter">Count: <span id="count"></span></span>
                        <button id="increment">Increment</button>
                    </div>
                `;

                // Bind methods and references
		// create new field incrementButton and countDisplay 
                this.incrementButton = this.shadow.querySelector('#increment');
                this.countDisplay = this.shadow.querySelector('#count');

                // create default _count field to store value
		_______________
                // Event listener for the button
                this.incrementButton.addEventListener('click', () => this.increment());
            }

            // Specify observed attributes count
            static get observedAttributes() {
                __________
            }

            // Called when the element is added to the DOM
            connectedCallback() {
                console.log('CounterElement added to the DOM');
                this.updateCount();
            }

            // Called when an observed attribute changes
            attributeChangedCallback(name, oldValue, newValue) {
                if (name === 'count') {
                    this._count = parseInt(newValue, 10) || 0;
                    this.updateCount();
                }
            }

            // Called when the element is removed from the DOM
            disconnectedCallback() {
                console.log('CounterElement removed from the DOM');
            }

            // Increment the count and update the attribute
            increment() {
                this._count += 1;
                this.setAttribute('count', this._count);
            }

            // Update the displayed count
            updateCount() {
                this.countDisplay.textContent = this._count;
            }
        }

        // Register the custom element
        _______________
    </script>
</body>

19
New cards

developer experience

user experience

•Once again, we meet two competing issues – DX (____ _____) and UX (_____ _____)

  • Frameworks may provide a better DX or support for legacy – they win and you should very much know them

  • UX requires raw speed

    • Best solution is a framework that provides a thin-ish layer at best and falls away if/when no longer needed (biodegradable deving!

20
New cards

web component

WC stands for ______ ______, a set of web platform APIs that enable the creation of reusable, encapsulated, and framework-agnostic custom HTML elements.

  • developer-defined HTML elements

  • custom elements with logic that integrate seamlessly into the DOM and CSS, using standard features immediately.

21
New cards

custom elements

web components

____ _________ are a subset of _____ ___ (wc).

22
New cards

True

Are standard HTML global attributes automatically part of web components?

for example, you can define the class and id of wc, they worked just like other standard components

23
New cards

True

: Does the native event system (addEventListener) work with web components?

24
New cards

light

the normal exposed part of the DOM in a web component is called ___________ DOM

25
New cards

shadow

What is the hidden or protected part of a web component called?
_________ DOM

26
New cards

False

Do you have to use the protected (shadow) DOM when making a web component?

  • this is recommended for encapsulation

27
New cards

shadow DOM content

What is content enclosed within a web component called

  • ________ ________ ______.

28
New cards

super()

What function is called in the constructor when creating a web component?

__________

  • this is called to inherit build in functionality of HTML elements

29
New cards

connectedCallback()

What method is fired when a web component is mounted in the page?
__________

30
New cards

connectedCallback()

Where should most of the DOM work be done in a web component?

______________

31
New cards

DOMContentLoaded()

_________ fires once per document:

  • It runs when the whole HTML document is fully parsed.

  • It does not account for dynamically added web components.

32
New cards

:not(:defined)

What CSS pseudo-class is used to address styling issues with web components that aren’t rendered?
_________________

33
New cards

disconnectedCallback()

What method is fired when a web component is removed from the page?

____________

34
New cards

static get observedAttributes

attributeChangedCallback

How do you know if attributes are modified in a web component?

first we want to Specify which attributes to observe

_________________() {
    return ['data-value', 'title'];
  }

then, react to attribute changes:


  // Step 2: React to attribute changes
  __________(name, oldValue, newValue) {
    console.log(`Attribute ${name} changed from ${oldValue} to ${newValue}`);
    // Add your custom logic here
    if (name === 'data-value') {
      this.updateValue(newValue);
    }
  }

35
New cards

adoptedCallback()

called each time the element is moved to a new document.

36
New cards

attributeChangedCallback():

called when attributes are changed, added, removed, or replaced. See Responding to attribute changes for more details about this callback.

37
New cards

False

True or False: The constructor lifecycle method of a Web Component is triggered when the component is removed from the DOM.

38
New cards

observedAttributes

constructor

connectedCallback

disconnectedCallback

adoptedCallback

attributeChangedCallback

define

life cycle of custom element:

// Create a class for the element
class MyCustomElement extends HTMLElement {
  static __________= ["color", "size"];

  _______() {
    // Always call super first in constructor
    super();
  }

  ________() {
    console.log("Custom element added to page.");
  }

  _________() {
    console.log("Custom element removed from page.");
  }

  _______() {
    console.log("Custom element moved to new page.");
  }

  _________(name, oldValue, newValue) {
    console.log(`Attribute ${name} has changed.`);
  }
}

customElements.______("my-custom-element", MyCustomElement);

39
New cards

DOMContentLoaded

connectedCallback

shadow

just like it is best for light shadows to run DOM code in the event ___________, it is also best to run DOM code inside the event __________ for wc.

  • if we using ______ DOM, we can setup innerHTML in constructor since wc is encapsulated and does not rely on main DOM

  • if not, we should do it in cc

40
New cards

backward

Web components do not replace frameworks they should just work with them. Anyone hating on them should hate on HTML elements because that is what they are. If a framework relies solely on synthetic components it is more ____ thinking than forward thinking.

41
New cards

<template>

What element is used to store reusable markup inside a web component?

42
New cards

Publish-subscribe

What pattern can be implemented using custom events in web components?

______-______ pattern

43
New cards

false

Do web components replace most web frameworks?

44
New cards

False

True or False: Web Components are fundamentally different from regular HTML elements.

45
New cards

lit

What is a close-to-the-platform library for Web Component creation?

46
New cards

div

Q: Why should developers be cautious about AI-generated markup?
A: AI often reinforces common, mediocre patterns, leading to excessive use of _______ tags.

47
New cards

inefficient

Q: What is a risk of AI favoring statistically common concepts in web development?
A: It can lead to homogenized, uninspired designs and _____ markup.

48
New cards

creativity

Q: What is one strategy to adapt to AI’s influence on web development?
A: Focus on refining AI-generated output and emphasizing _____ in design.

49
New cards

56

user experience / UX

Mobile now accounts for ___% of all website traffic, but mobile commerce lags behind due to terrible ___.

50
New cards

19

2

On average, mobile sites take ___ seconds to load over a 3G network, but users expect pages to load within ___ seconds.

51
New cards

Reliable

fast

engaging

Progressive Web Applications aim to be ___, ___, and ___.

52
New cards

progressive web applications

what is PWA: _____________________

an app that's built using web platform technologies, but that provides a user experience like that of a platform-specific app.

Like a website, a PWA can run on multiple platforms and devices from a single codebase. Like a platform-specific app, it can be installed on the device, can operate while offline and in the background, and can integrate with the device and with other installed apps.

53
New cards

Service Workers

proxy

requests

offline

Installed

manifest

Prefetches

Background

PWA

___ are central to PWAs as they allow for offline access and caching.

act as ___ servers that sit between web applications, the browser, and the network (when available)

  1. Controls Network ____:

    • Service Workers can intercept and modify network requests, acting as a proxy between the browser and the server. This allows them to determine whether to serve cached data or fetch resources from the network, improving efficiency.

  2. Supports _____ Access:

    • By caching resources (HTML, CSS, JavaScript, images, etc.), Service Workers ensure that users can interact with the app even when offline. For example, you can still read saved articles in a news app while disconnected from the internet.

  3. Enables "_____" Feel:

    • With a Service Worker and a _____ file, PWAs can behave like native apps. Users can "install" PWAs, and they’ll run in standalone windows, enhancing the app-like experience.

  4. ______ and Improves Performance:

    • Service Workers can pre-cache assets, reducing load times for frequently accessed content. This makes the application faster and more responsive.

  5. Runs in the ______:

    • Unlike Web Workers, which are tied to active web pages, Service Workers can run beyond the lifecycle of the page. This means they can handle tasks like syncing data or delivering push notifications even when the webpage is closed.

  6. Integral to ____:

    • Service Workers are a cornerstone of PWAs because they enable offline capability, better performance, and push notifications. Together with features like the manifest file, they bridge the gap between web and native apps.

<p>___ are central to PWAs as they allow for offline access and caching.</p><p>act as <strong>___ servers that sit between web applications, the browser, and the network</strong> (when available)</p><ol><li><p><strong>Controls Network ____</strong>:</p><ul><li><p>Service Workers can intercept and modify network requests, acting as a proxy between the browser and the server. This allows them to determine whether to serve cached data or fetch resources from the network, improving efficiency.</p></li></ul></li><li><p><strong>Supports _____ Access</strong>:</p><ul><li><p>By caching resources (HTML, CSS, JavaScript, images, etc.), Service Workers ensure that users can interact with the app even when offline. For example, you can still read saved articles in a news app while disconnected from the internet.</p></li></ul></li><li><p><strong>Enables "_____" Feel</strong>:</p><ul><li><p>With a Service Worker and a _____ file, PWAs can behave like native apps. Users can "install" PWAs, and they’ll run in standalone windows, enhancing the app-like experience.</p></li></ul></li><li><p><strong>______ and Improves Performance</strong>:</p><ul><li><p>Service Workers can pre-cache assets, reducing load times for frequently accessed content. This makes the application faster and more responsive.</p></li></ul></li><li><p><strong>Runs in the ______</strong>:</p><ul><li><p>Unlike Web Workers, which are tied to active web pages, Service Workers can run beyond the lifecycle of the page. This means they can handle tasks like syncing data or delivering push notifications even when the webpage is closed.</p></li></ul></li><li><p><strong>Integral to ____</strong>:</p><ul><li><p>Service Workers are a cornerstone of PWAs because they enable offline capability, better performance, and push notifications. Together with features like the manifest file, they bridge the gap between web and native apps.</p></li></ul></li></ol><p></p>
54
New cards

Manifest

A ___ file centralizes metadata for PWAs, such as icons and themes.

55
New cards

3

  • Users abandon sites that take more than ___ seconds to load.

56
New cards

Reach

availability

Progressive Web Apps attempt to balance the richness of a native application with the r___ and a___ of a web application.

57
New cards

PWA

Ajax

service workers are to _______ as XMLHttpRequest to ____

58
New cards

network only

what kind of service worker pattern is this _______________

<p>what kind of service worker pattern is this _______________</p>
59
New cards

cache only

what kind of service worker pattern is this _______________

<p>what kind of service worker pattern is this _______________</p>
60
New cards

cache then network

what kind of service worker pattern is this _______________

<p>what kind of service worker pattern is this _______________</p>
61
New cards

cache, falling back to network

what kind of service worker pattern is this _______________

<p>what kind of service worker pattern is this _______________</p>
62
New cards

network, falling back to cache

what kind of service worker pattern is this _______________

<p>what kind of service worker pattern is this _______________</p>
63
New cards

proxy

What is the main purpose of a Service Worker in a web application?

  • Answer: A Service Worker acts as a _______ between the client and the server, allowing interception and control of network requests, often caching responses for offline use.

64
New cards

requests

The Service Worker API allows developers to intercept network __________ and control them, often serving cached responses.

65
New cards

localhost effect

A major challenge of web development compared to local development is the _____________ _______, where local environments are stable, but real-world networks are not.

66
New cards

offline

One benefit of Service Workers is enabling __________ browsing, where users can access some content even when the network is unavailable.

67
New cards

false

true/false: service workers can modify browser DOM directly

68
New cards

B

What is the primary motivation for using a Service Worker?
A) Speeding up the initial page load
B) Reducing dependency on a stable network
C) Replacing a traditional server
D) Enhancing JavaScript performance

69
New cards
self.addEventListener("fetch", (event) => {
    event.respondWith(
        caches.match(event.request).then((response) => {
            return response || fetch(event.request);
        })
    );
});

Write a Service Worker Fetch Event Handler:

  • Question: Write a Service Worker fetch event handler that serves cached files first and fetches from the network if not available.

70
New cards
navigator.serviceWorker?.register(/service-worker.js)

suppose your service worker is defined at /service-worker.js, register it

71
New cards
self.addEventListener("install", (event) => {
    event.waitUntil(
        caches.open(CACHE).then((cache) => {
            return cache.addAll(ASSETS);
        })
    );
});

Write a Service Worker Fetch Event Handler:

  • Question: Write a Service Worker install event handler, that cache files ASSET to CACHE

72
New cards
{
  "name": "MyApp",
  "short_name": "App",
  "start_url": "/home",
  "display": "standalone"
}

what is the manifest of a PWA named MyApp, or App, and start url at /home`

73
New cards

white

what is the final color after everything is loaded and element is defined

<custom-message>This is a custom message</custom-message>
custom-message:not(:defined) {
  color: gray;
}

custom-message:defined {
  color: blue;
}

custom-message{
  color: white;
}

74
New cards

gray

what is the final color after everything is loaded and element is undefined

<custom-message>This is a custom message</custom-message>
custom-message:not(:defined) {
  color: gray;
}

custom-message:defined {
  color: blue;
}

custom-message{
  color: white;
}