Introduction to Web Technologies

Benny Powers Principal UX Engineer

Portions © WHATWG (CC-BY), MDN (CC-BY-SA)

Introduction to Web Technologies

In this Presentation

  1. HTML for Document Structure
  2. CSS for Document Style
  3. JavaScript for Interactivity
  4. HTTP and the Browser
  5. Developer Tools

Introduction to Web Technologies

What is HTML?

The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect.

Sir Tim Berners-Lee
decorative brickwork on the side of a building
"Brickwork" by Sociotard

What is HTML?

HTML is the foundation of the World Wide Web and the core of every website and web app. Mastering HTML is crucial to developing performant, accessible, and successful web applications.

Sir Tim Berners-Lee, 2014, in suit jacket & blue tie HTML5

  • HyperText Markup Language
  • Sir Tim Berners Lee, CERN, 1993
  • Structured Text interconnected by hyperlinks

What is HTML?

HTML is an open standard, anyone can freely read, copy, distribute, and implement it. The HTML Living Standard is published by the WHATWG under the Creative Commons Attribution 4.0 International license.

  • W3C: World Wide Web Consortium
  • WHATWG: Web Hypertext Application Technology Working Group

W3C > WHATWG formalized in 2019

What is HTML?

Each HTML document is a tree of elements containing metadata, text, and other contents. An HTML element is a tag name with optional attributes, and content. Elements can contain whitespace, text, comments, or other elements.

<p>
  The paragraph tag contains
  <em>phrasing</em> content.
</p>

What is HTML?

Attributes

HTML attributes live in the open tag, after the tag name. They are key-value pairs separated by =, where the value is surrounded by quotation marks.

<a href="https://redhat.com">Red Hat</a>

Some attributes, like id, are global. Others, like href, are specific to certain elements.

What is HTML?

Void Elements

Some elements, like <img>, are void elements AKA self-closing, meaning they have no content and do not have a closing tag

  <img alt="red fedora with black band"
+      src="/images/red-hat-logo.svg">
-      src="/images/red-hat-logo.svg"></img>

What is HTML?

The Document Tree

The root element of every HTML document is the <html> element. It has two children: <head> and <body>.

<head> contains document metadata and links to subresources, <body> is where the document content goes.

<!doctype html>
<html lang="en">
  <head>
    <title>Basic HTML Page</title>
  </head>
  <body>
    <main>
      <p>Body content lives in landmarks</p>
    </main>
  </body>
</html>

What is HTML?

Landmarks

Landmark elements define the large-scale structure of the page

  • <main> for the main content
  • <header> for banners, titles, etc.
  • <footer> for content which comes after the main
  • <aside> for content which diverges from the main flow

Note:

All page content must be contained within a landmark.

<header>
  <h1>Page Structure Matters</h1>
</header>
<main>
  <p>Body content lives in landmarks</p>
</main>
<aside>
  <p>This also helps SEO</p>
</aside>
<footer>
  <p>And creates accessible web pages</p>
</footer>

Introduction to Web Technologies

Semantic HTML

All our work, our whole life is a matter of semantics, because words are the tools with which we work... Everything depends on our understanding of them.

Felix Frankfurter
bookshelves in a library aisle
"Bookshelves" by Germán Poo-Caamaño

Semantic HTML

Meaning in Structure

HTML elements have meanings. The meaning which HTML elements convey to their context and contents is called HTML semantics It's important to use the correct semantics so that people and machines can correctly interpret the intent of your documents.

Incorrect semantics can lead to broken experiences for many users, and ultimately lost revenue for the owners of the page.

Semantic HTML

Sectioning Content

Defines the scope of <header> and <footer> elements

  • <article>
  • <aside>
  • <nav>
  • <section>

Semantic HTML

Document Headings

  • <h1>, <h2>, <h3>, <h4>, <h5>, <h6>
  • Only one <h1> per page
  • Headings must not skip ahead, so no <h1> to <h3>
  • But you may skip back, to <h6> to <h2>
  • Phrasing content must intervene between headings

Semantic HTML

Interactive Content

Interactive content is how your users interact with the page, the web server, or another server entirely.

  • hyperlinks: <a href>
  • multimedia: <audio controls> and <video controls>
  • forms: <button>, <input>, <textarea>, <select>, <label>

Note:

Ensure all your interactive content is accessible by keyboard, not just by pointers like tap or mouse.

Semantic HTML

Div Soup

<div> has no meaning whatsoever. It's used only for styling or scripting. Much better to use the sectioning elements or specific interactive elements

div soup from twitter.com. Screenshot taken by Chris Coyier in
2021

Semantic HTML

Don't add interactivity to <div>

<div onclick="sendMessageToServer()">Submit</div>

Do use the correct semantic element

<button type="submit"
        onclick="sendMessageToServer()"></button>

Semantic HTML

Some Interesting Elements

HTML already comes with a number of interesting built-in elements:

  • <time> to mark a point in time
  • <mark> to highlight a portion of text
  • <code> to represent source code
  • <article> for an independent, distributable content, e.g: blog post, comment, interactive widget, etc
  • <address> contact information for the page or <article>
  • <bdi> for טקסט דו-כיווני: content in any direction!
  • <dl>, <dt>, and <dd>, the Definition list, term, and definition elements (since in HTML 1.0!)

And many more, listed in the living standard

Semantic HTML

Disclosure Widgets

HTML is enough to write entire apps. <details> and <summary> can hide or show content by activating the disclosure widget. Add the open boolean attribute to make them open by default.

for example...
<details open>
  <summary>Hide details</summary>
  <dl>
    <dt>Height</dt> <dd>1.2m</dd>
    <dt>Weight</dt> <dd>150kg</dd>
    <dt>Hair Colour</dt> <dd>Brown</dd>
  </dl>
</details>

Semantic HTML

Dialogs

The <dialog> element is a web-native way to present information to the user in a popup window or modal dialog.

Show Modal

<button id="showModal" onclick="dialog.showModal()">Show Modal</button>
<dialog id="dialog" onclose="output.value=`${dialog.returnValue} selected`">
  <form method="dialog">
    <label>Choose a Platform:
      <select onchange="confirm.value=this.value">
        <option disabled selected>Pick One</option>
        <option value="iOS">iOS (proprietary)</option>
        <option value="Google">Google (proprietary)</option>
        <option value="Windows">Windows (proprietary)</option>
        <option value="Web">Web (open)</option>
      </select>
    </label>
    <button id="confirm">Confirm</button>
  </form>
</dialog>
<output id="output"></output>

Introduction to Web Technologies

Embedded Content

A picture is worth a thousand words

blueberry muffins
"Blueberry Muffins for Breakfast" by Steven Jackson

Embedded Content

Images

The <img> element embeds an image in the page. It must have an alt attribute that describes its contents, unless solely for decoration. It's a void element with no content. Use loading="lazy" to defer loading the image.

<img alt="" src="flourish.png">
<img alt="Children playing in the sun"
     loading="lazy"
     src="playground.jpg">
<img role="presentation" src="flourish.png">
<img alt="Children playing in the sun"
     loading="lazy"
     src="playground.jpg">

Embedded Content

Picture

The <picture> element allows more control over which images to load. Art direction is the process of loading different images depending on client conditions.

<picture>
  <source srcset="shire-night.png"
          media="(prefers-color-scheme: dark)">
  <img alt="The Shire, a peaceful, verdant village"
       src="shire-day.png">
</picture>

Embedded Content

Video

The <video> element provides video playback on web pages. Sites like YouTube use <video> to play user content.

<video muted autoplay poster="thumbnail.jpg" width="500">
  <source type="video/webm" src="big-buck-bunny.webm">
  <source type="video/mp4" src="big-buck-bunny.mp4">
</video>

Embedded Content

Audio

The <audio> element provides sound playback on web pages. Like <video>, you can provide multiple sources

<audio controls>
  <source type="audio/ogg" src="hatikva.ogg">
  <source type="audio/mpeg" src="hatikva.mp3">
</video>

Embedded Content

Iframes

The <iframe> element embeds content from another website within your page.

<iframe src="https://ux.redhat.com" loading="lazy"
        width="100%" height="500px"></iframe>

Embedded Content

Canvas

The <canvas> element doesn't do much on it's own, but with the canvas scripting or WebGL APIs, it is used to output arbitrary graphics like games, audio visualizations, animations, etc.

WebGL Aquarium Demo

Semantic HTML

HTML Forms

When people talk about Web 2.0, they mean that when the Internet, the World Wide Web, first became popular, it was one-way only.

Edward Snowden
several adults performing tai chi in a park
"World Tai Chi Day" by Brian Robinson

HTML Forms

Starting with HTML 2 in 1995, HTML gained the ability to receive user input via <form>, and not just display author's content. Prior to <form>, the only way to publish content on the web was to write an HTML document and publish it to a web server via FTP, for example.

The widespread adoption of <form> led to a user-content revolution which came to be known as "Web 2.0". Wikipedia, Twitter, MySpace ⇨ Facebook, Flickr ⇨ Instagram all owe their existence to HTML forms.

HTML Forms

Form controls

Careful:

Controls must be labelled. Placedholders are not enough.

HTML Forms

Fieldsets

Form fields can be grouped into fieldsets. Fieldsets can have a <legend> to describe their contents, and if they are disabled, it disables all of its children.

Disabling fieldsets disables their children

HTML Forms

HTTP Forms

Forms can have an action and a method, which determines how and where they send their contents.

<form method="POST" action="/users/new.php">
  <label>Username <input name="username" type="text"></label>
  <label>Password <input name="password" type="password"></label>
  <button>Register</button>
</form>
Register
POST /users/new.php HTTP/1.1
Host: localhost:8080
Content-Type: application/x-www-form-urlencoded
Content-Length: 31

username=RedHat&password=Beyond

HTML Forms

HTML Forms work without, and in fact predate JavaScript. Web apps don't need JS to provide interactive experiences & should provide fallbacks when JS is unavailable.

<form id="searchForm" action="/search">
  <label>🔍 <input name="query" type="search"></label>
  <button>Search</search>
</form>

<script>
  searchForm.addEventListener('submit', async function (event) {
    event.preventDefault();
    const results = await fetch('/search', {
      body: new FormData(this),
      method: 'post',
    });
  });
</script>

Introduction to Web Technologies

What is CSS?

We wanted people to use HTML. But we also wanted people to say something about font size, colours, typography, layout, margins and shadows and such. Because otherwise they wouldn’t have used HTML.

Håkon Wium Lie
colourful painting
"Nightmare" by Jelene

Pr. "HAWK-uhn VEE-yumm LEE-yeh"

What is CSS?

CSS is the presentation layer of an HTML document. It controls things like colours, fonts, layouts, and animations.

Håkon Wium Lie CSS3

  • Cascading Style Sheets
  • Håkon Wium Lie, W3C, 1996
  • Separates presentation from content

Pr. "HAWK-uhn VEE-yumm LEE-yeh"

What is CSS?

Syntax

Stylesheets are made up of rules. Each rule has a selector list of one or more selectors, followed by a set of curly braces { }. Inside the braces is a list of declarations, separated by semicolons ;. Each declaration has a property on the left side, and one or more values on the right side, separated by a colon.

h1, h2 {
  font-weight: bold;
  color: purple;
}

What is CSS?

The Cascade

CSS Rules cascade, meaning they layer onto each other in the order they are declared. The cascade and selector specificity determine how conflicts are resolved in stylesheets.

h1, h2 {
  font-style: italic;
  color: purple;
}

h2 {
  color: red;
}

ASK: what colour will the h2 be? what style?

What is CSS?

Colours

Colours in CSS can be represented multiple ways.

Hex Values
#FFFFFFFF
RGB function
rgb(255, 255, 255, 1);
HSL function
hsl(360deg 100% 100% / 100%);
Named Colours
cornflowerblue;
rebeccapurple;
hotpink;
Others
hwb(), lch(), lab(), color(color-space)

What is CSS?

Box Model

CSS' box model defines elements' dimensions and positions in terms of surrounding boxes. Boxes' dimensions are composed of margin separating it from other boxes, a border surrounding itself, padding separating content from the border, and the content itself.

Boxes can have one of two "outer display types", which determine how the browser lays them out on the page. Block elements break onto a new line and have margins, border, and padding which push other elements away. Inline elements do not break onto a new line and their blockwise box properties do not push away other elements.

screenshot from firefox' box model developer tools

What is CSS?

Block and Inline

<p>
  Paragraphs have block display,
  while <strong>strong is inline</strong>
  <h3>Headings</h3> are block-level, though and
  should not be nested in ps
</p>

Paragraphs have block display, while strong is inline

Headings

are block-level, though and should not be nested in ps

What is CSS?

Logical Properties

CSS Provides logical box-model properties which make your layouts more resiliant and internationalizable. Instead of referring to directions top, right, left, bottom, we have the block and inline axes and the start and end directions:

top
block-start
right
inline-end
left
inline-start
bottom
block-end

LTR Block Inline

RTL Block Inline

Start: End:

What is CSS?

Flexbox

CSS boxes also have an "inner display type" which governs how their contents are laid out. The display: flex; declaration turns a box into a flex box, which means the contents will flex to fill the available space, according to the rules you define.

diagram of flexbox terms: flex container, main axis, cross axis, start, end,
flex item

What is CSS?

CSS Grid

CSS Grid is a powerful feature which makes much of legacy CSS frameworks like bootstrap obsolete. Flexbox works primarily along a single dimension. For two-dimensional grid layouts, use display: grid;.

diagram explaining css grid model terms: rows, gutters,
columns

Whenever creating page layouts, always reach for CSS Grid first before loading some css framework

What is CSS?

CSS Queries let you conditionally apply styles.

  • Media queries: based on device, screen size, or user settings
  • Feature queries: based on whether some CSS feature is supported
  • Container queries (🌠 new!): based on the containing box
  • Style queries (🤞 upcoming): based on the values of other styles

What is CSS?

Responsive Design

The practice of using media queries to change page layout depending on device type and screen size.

main { /* mobile */
  display: grid;
  grid-template-columns: 1fr;
}
@media (min-width: 500px) { /* tablet */
  main { grid-template-columns: 2fr 1fr; }
}

@media (min-width: 1000px) { /* desktop */
  main { grid-template-columns: 1fr 4fr 1fr; }
}
@media (print) {
  main {
    display: block;
  }

  nav {
    display: none;
  }
}
mobile phone responsive layout laptop responsive layout print responsive layout

What is CSS?

More CSS Features

  • CSS counters
  • scroll-snap
  • masonry grids
  • typography features
  • pointer-events

Introduction to Web Technologies

What is JavaScript?

Any app that can be written in JavaScript, will eventually be written in JavaScript.

Jeff Atwood

Java is to JavaScript as ham is to hamster.

Jeremy Keith

cappuccino in a blue demitasse next to a blank spiral-bound notebook with
closed pen resting on top

What is JavaScript?

JavaScript provides custom interactivity to web pages and applications. It is also a general purpose, multiparadigm language used in server-side, edge, and embedded applications as well.

Brendan Eich in suit jacket JS

  • Officially ECMAScript or es
  • Brendan Eich, Mozilla, 1995
  • IEEE 7th most popular language
  • StackOverflow most popular language

ECMA International is the standards body in charge of the language specification

What is JavaScript?

Progressive Enhancement

Before writing any JavaScript, it's critical to ensure that your HTML and CSS are correct, comprehensive, and sufficient. Progressive enhancement is the practice of using JavaScript to add additional features and niceties to an already complete application experience.

Sometimes JavaScript fails to load. Some users disable javascript in their browsers. Many users use low-power devices, and the cost of parsing and executing large JS bundles is non-trivial.

What is JavaScript?

Data Types

JavaScript is a dynamically typed, JIT-compiled language. It's data types are

  • string (utf-8)
  • number (including both integers and floats)
  • boolean
  • object
  • undefined

In JavaScript, everything is an object.

What is JavaScript?

Variables

venn diagram: var and let are reassignable, let and const are
block-scoped JavaScript variables are declared with var, let, or const. Primitive types (string, number, boolean) equate by value. Object types are assigned and compared by reference, not by value.

assert(1 === 1);                    // ✅
assert('RedHat' === 'RedHat');      // ✅
assert(true === true);              // ✅
const obj = { hello: 'world' };
assert(obj === obj);                // ✅
assert(obj === { hello: 'world' }); // ❌
const obj = { hello: 'world' };
      obj = { shalom: 'haver' };
      // => TypeError: invalid assignment to const 'obj'

obj.shalom = 'haver';
console.log(obj);
// => { hello: 'world', shalom: 'haver' }

What is JavaScript?

Iteration

while (bool) {
  // ...
}

do {
  // ...
} while (bool)
for (let i = 1; i <= 100; i++) {
  // ...
}

for (const item of iterator) {
  // ...
}
Object.keys({ hello: 'world' });    // ['hello']
Object.values({ hello: 'world' });  // ['world']
Object.entries({ hello: 'world' }); // [['hello', 'world']]

Object.fromEntries(
  Object.entries({ hello: 'world' })
    .map(([ key, value ]) =>
      [translate(key), translate(value)])
); // { bonjour: 'le monde' }

What is JavaScript?

Conditionals

if (key === 'A')
  return 1;
else if (key === 'B')
  return 2;
else
  return 3;
switch (key) {
  case 'A': return 1;
  case 'B': return 2;
  default: return 3;
}
return key === 'A' ? 1
     : key === 'B' ? 2
     : 3;

What is JavaScript?

Functions

JavaScript functions are first-class: they are value expressions like any other. They're also objects, like everything else in JS.

function inc(x) { return x + 1; }
const double = x => x * 2;
const pow = exp => x => x ** exp;

inc.call(null, 3);     // 4
[1, 2, 3].map(inc);    // => [2, 3, 4]
[1, 2, 3].map(double); // => [2, 4, 6]
[1, 2, 3].map(pow(2)); // => [1, 4, 9]
async function getJSON(url) {
  try {
    const response = await fetch(url);
    const json = await response.json();
    return json;
  } catch {
    throw new Error('Could not fetch');
  }
}
function* iterInts() {
  let state = -1;
  while(true)
    yield state++;
}

for (const int of iterInts()) {
  if (int < 100) console.log(int);
  else break;
}

What is JavaScript?

Classes

  • Familiar OOP syntax and concepts
  • Maps well to DOM
  • Powerful and growing feature set
class Car extends Vehicle {
  static wheels = 4;

  #locked = false;
  #childLockEngaged = false;

  get locked() { return this.#locked; }
  set locked(value) {
    if (!this.#childLockEngaged)
      this.#locked = value;
  }

  constructor(doors = 2) {
    super();
    this.doors = doors;
  }
}
const car = new Car();
      car.drive();

assert(car instanceof Vehicle);
console.log(car.constructor)                     // class Car {...}

'drive' in Object.getPrototypeOf(car);           // true
'drive' in Object.getPrototypeOf(new Vehicle()); // true

firefox dev tools prototype chain

Not copies - prototype links

Introduction to Web Technologies

Document Object Model

Anything found in an HTML document can be accessed, changed, deleted, or added using the Document Object Model

W3C

screenshot of elements inspector from firefox dev tools

Document Object Model

The DOM: Document Object Model

As the browser downloads an HTML page, it instantiates a DOM for the document.

  • Every HTML element becomes an element node
  • The <html> element becomes the root document node
  • HTML Text content becomes text nodes
  • Comments become comment nodes

This happens while the server streams HTML to the client, but <script> elements and other subresources can halt streaming DOM construction and impair page performance.

Document Object Model

Manipulating the Document

  • querySelector(selector)
  • node.append()
    node.remove()
  • document.createElement(tagName)
  • element.setAttribute(name, value) element.removeAttribute(name) element.toggleAttribute(name)

Document Object Model

Events

Node inherits from EventTarget

  • click / tap / scroll / mouseenter / mouseleave
  • keyup / keydown
  • focus / blur
  • dragstart / dragstop / drop

Events have target and path properties which provide rich detail about the state of the DOM.

Document Object Model

Event Listeners

document.querySelector('canvas')
  .addEventListener('mousemove', function(event) {
    const ctx = this.getContext('2d');
    ctx.fillStyle = 'black';
    ctx.fillRect(event.clientX, event.clientY, 2, 2);
  });

Introduction to Web Technologies

What are Web Components?

Because web components are native to the web, they can travel to any web-based environment.

Brad Frost

gears in a machine

What are Web Components?

Custom Elements

In the DOM, each element relates to a specific class. Custom Elements are HTML tags containing a hyphen which are linked to a user-defined JavaScript class through the customElements namespace.

class FancyElement extends HTMLElement {
  fanciness = 11;
}

customElements.define('fancy-element', FancyElement);

What are Web Components?

The <template> Element

Parse HTML into the DOM once, clone it cheaply many times.

<template id="fancy-template">
  <article>
    <h2>Name</h2>
    <p class="description"></p>
    <footer><a>Read More</a></footer>
  </article>
</template>
document.getElementById('fancy-template')
  .content
  .cloneNode(true);

What are Web Components?

Shadow DOM

A private, encapsulated DOM subtree, attached to an element.

firefox element inspector highlighting an open shadow root

  • DOM isolation (unique IDs)
  • Style Encapsulation (simple selectors)
  • Event Retargeting

What are Web Components?

The <slot> Element

Projects contents from the "light" DOM into positions in the Shadow Root.

firefox element inspector showing a slotted element
::slotted(h2) {
  color: var(--rh-color-brand-red-on-light);
}

What are Web Components?

Styling Web Components

CSS Custom Properties

  • Inherit ∴ pierce shadow boundaries
  • Useful for theming, animation, conditional CSS

CSS Shadow Parts

  • Expose shadow elements as stylable
  • Makes author-selected private elements public

What are Web Components?

CSS Custom Properties

Shadow CSS:

#content {
  background: var(--content-background, transparent);
}

Light CSS:

x-element {
  --content-background: red;
}

What are Web Components?

CSS Shadow Parts

Shadow DOM:

<div id="content" part="content">
  <slot></slot>
</slot>

Light CSS:

x-element::part(content) {
  background: red;
  padding: 2em;
}

What are Web Components?

The Future of Web Components

  • CSS / HTML Modules
  • Declarative Shadow DOM
  • Form-Associated Custom Elements
  • Declarative Custom Elements
  • DOM Parts / Template Instantiation

Introduction to Web Technologies

Thanks to Nikki Massaro Kaufman for her help on the JS section