Remove Front End

pull/96/merge
Yangshun Tay 7 years ago
parent c34b341a36
commit 264f6cf7d8

@ -1,201 +0,0 @@
Accessibility
==
## Glossary
- **Accessibility** -
- **WAI-ARIA** - Web Accessibility Initiative - Accessible Rich Internet Applications. Commonly shortened to ARIA.
## What is Accessibility?
Making sure that the content and the websites we create are usable to people with impairments or disabilities.
## WebAIM Checklist
The following is a checklist that contains recommendations for implementing HTML-related principles and techniques for those seeking WCAG 2.0 conformance (it is NOT the Web Content Accessibility Guidelines (WCAG) 2.0).
- **Perceivable** - Web content is made available to the senses - sight, hearing, and/or touch.
- Text Alternatives: Provide text alternatives for any non-text content.
- Time-based Media: Provide alternatives for time-based media.
- Adaptable: Create content that can be presented in different ways (for example simpler layout) without losing information or structure.
- Distinguishable: Make it easier for users to see and hear content including separating foreground from background.
- **Operable** - Interface forms, controls, and navigation are operable.
- Keyboard Accessible: Make all functionality available from a keyboard.
- Enough Time: Provide users enough time to read and use content.
- Seizures: Do not design content in a way that is known to cause seizures.
- Navigable: Provide ways to help users navigate, find content, and determine where they are.
- **Understandable** - Content and interface are understandable.
- Readable: Make text content readable and understandable.
- Predictable: Make Web pages appear and operate in predictable ways.
- Input Assistance: Help users avoid and correct mistakes.
- **Robust** - Content can be used reliably by a wide variety of user agents, including assistive technologies.
- Compatible: Maximize compatibility with current and future user agents, including assistive technologies.
**Source:** http://webaim.org/standards/wcag/checklist
## Focus
- Making sure your application has a sensible tab order is important.
- HTML forms and inputs are focusable and handle keyboard events by default.
- Focus tab order relies on the DOM order in the HTML.
- Be careful when using CSS when changing the order of elements on the screen, it can cause the order to be unintuitive and messy.
- `tabindex` attribute:
- `-1`: Not in the natural tab order, but programatically focusable using JavaScript with `focus()` method. Useful for off-screen content which later appears on screen. Children elements are **NOT** pulled out of the tab order.
- `0`: In the natural tab order and can be programatically focused.
- `1` (bigger than 1): In the natural tab order but jumped in front of the tab order regardless of where it is in the DOM. It can be considered an anti-pattern.
- Add focus behavior to interactive controls, like buttons, tabs, dropdowns, stuff that users will interactive with.
- Use skip links to allow users to skip directly to the main content without having to tab through all the navigation.
- `document.activeElement` is useful in tracking the current element that has focus on.
## Semantics
- Using proper labeling not only helps accessibility but it makes the element easier to target for all users!
- Use `<label>` with `for` attributes for form elements.
- Use `alt` attribute for `<img>` elements. Alt text must describe the image.
- TODO
## Navigating Content
- MacOS comes built-in with VoiceOver. Press <kbd>CMD</kbd> + <kbd>F5</kbd> to activate.
- Activate Web Rotor with <kbd>Ctrl</kbd> + <kbd>Option</kbd> + <kbd>U</kbd>. Web Rotor displays landmarks, headings, links and more on the page and allows you to jump to them directly.
- Heading weight should be decided by its importance on the page and not how big it should look, as the heading tag chosen affects the order the headings are listed on screen readers.
- Use HTML5 semantic tags like `<main>`, `<nav>`, `<header>`, `<aside>`, `<article>`, `<section>`, `<footer>` to indicate landmarks on the page.
## ARIA
- Express semantics that HTML can't express on its own.
- Accessibility tree = DOM + ARIA.
- ARIA attributes
- Allow us to modify the accessibility tree before they are exposed to assistive technologies.
- DO NOT modify the element appearance.
- DO NOT modify element behaviour.
- DO NOT add focusability.
- DO NOT add keyboard event handling.
- E.g. for custom checkboxes, adding ARIA attributes is not sufficient, you will need to write your own JavaScript to emulate the native behaviour to synchronize the ARIA attributes and values with the actual visual state, such as toggling using clicks and hitting spacebar. It's probably not worth it to reinvent the wheel by writing your own custom widgets that already exist in HTML5.
- ARIA can add semantics to elements that have no native semantics, such as `<div>`. ARIA can also modify element semantics.
- ARIA allows developers to create accessible widgets that do not exist in HTML5, such as a tree widget.
- `aria-role` attributes tell assistive technologies that the element should follow that role's accessibility patterns. There are well-defined roles in the HTML spec. Do not define them on your own.
- `tabindex="0"` is usually added to it elements that have `role` added so that it can be focused.
- Assistive labelling
- `aria-label` is useful for labelling buttons where the content is empty or contains only icons.
- `aria-labelledby` is similar to `<label>` elements, and can be used on any elements.
```html
/* Normal label example */
<input type="radio" id="coffee-label">
<label for="coffee-label">Coffee</label>
/* aria-labelledby example */
<div role="radio" aria-labelledby="coffee-label"></div>
<span id="coffee-label">Coffee</span>
```
- ARIA Relationships
- ARIA relationship attributes create semantic relationships between elements on the page. The `aria-labelledby` attribute in the previous example indicates that the `<div>` is labelled by the element with that `id`.
- Possible relationship attributes include `aria-activedescendent`, `aria-describedby`, `aria-labelledby`, `aria-owns`, `aria-posinset` and `aria-setsize`.
- With ARIA, you can expose only relevant parts of the page to accessibility tree. Elements can be hidden via:
- Setting `visibility`: `<button style="visibility: hidden">`.
- Setting `display`: `<button style="display: none">`.
- HTML5 `hidden` attribute: `<span hidden>`. This makes the element hidden to everyone.
- `aria-hidden` attribute: `<div aria-hidden="true">`. This makes the element hidden to screenreaders too. Note that `aria-hidden` attribute requires an explicit value of `true` or `false`.
- Technique for screenreader-only text:
```
.screenreader {
position: absolute;
left: -1000px;
width: 1px;
height: 1px;
overflow: hidden;
}
```
- `aria-live` attribute can be used to grab the assistive technology's attention to cause it to announce updates to the user. Practically, include `aria-live` attributes in the initial page load. The different `aria-live` values include:
- `off` (default) - Updates will not be presented unless the region is currently focused.
- `polite` - Assistive technologies should announce updates at the next graceful opportunity, such as at the end of speaking the current sentence on when the user pauses typing. Such as receiving new chat messages.
- `assertive` - Highest priority and assistive technologies should notify the user immediately. Examples include server status error alerts.
- `aria-atomic` attribute indicates whether the entire region should be presented as a whole when communicating updates. Such as a date widget comprising of multiple `<input>` fields for day/month/year. When the user changes a field, the full contents of the widget will be read out. It takes in a `true` or `false` value.
- `aria-relevant` attribute indicates what types of changes should be presented to the user.
- `additions` - Element nodes are added to the DOM within the live region.
- `removals` - Text or element nodes within the live region are removed from the DOM.
- `text` - Text is added to any DOM descendant nodes of the live region.
- `all` - Equivalent to the combination of all values, `additions removals text`.
- `additions text` (default) - Equivalent to the combination of values, `additions text`.
- `aria-busy` attribute indicates the assistive technologies should ignore changes to the element, such as when things are loading, for example after a temporary connectivity loss. It takes in `true` or `false`. It takes in a `true` or `false` value.
## Style
#### Introduction
- Ensure elements are styled to support the existing accessibility work, such as adding styles for `:focus` and the various ARIA states.
- Flexible user interface that can handle being zoomed or scaled up, for users who have trouble reading smaller text.
- Color choices and the importance of contrast, making sure we are not conveying information just with color alone.
#### Focus
- As much as possible, leave the default focus in place. Do not remove the `:focus` styling just because it does not fit into your design or looks odd! - A good technique is to use a similar styling as `:hover` for `:focus`.
- Some CSS resets would kill off the focus styling, so it's important to be aware of them and get them back.
#### Styling with ARIA
Consider using ARIA attributes in your CSS selectors to reduce some noise in your CSS. For custom toggle buttons, instead of doing this,
```html
<div class="toggle pressed" role="button" tabindex="0" aria-pressed="true"></div> /* On */
<div class="toggle" role="button" tabindex="0" aria-pressed="false"></div> /* Off */
.toggle.pressed {
...
}
```
you can do this instead:
```html
<div class="toggle" role="button" tabindex="0" aria-pressed="true"></div> /* On */
<div class="toggle" role="button" tabindex="0" aria-pressed="false"></div> /* Off */
.toggle[aria-pressed="true"] {
...
}
```
which removes the need for toggling the `press` class on the element.
#### Responsive Design
Responsive design is also beneficial for accessibility when zooming the page transforms the page into the mobile layout instead.
Use a meta viewport tag:
```
<meta name="viewport" content="width=device-width initial-scale="1">
```
`user-scalable=no` is an anti-pattern for accessibility.
Use relative units like `%`, `em` and `rem`. The differences are as follows:
- `%` - Relative to the containing block.
- `em` - Relative to the `font-size` of the parent.
- `rem` - Relative to the `font-size` of the root, which is the `<html>` element.
Interactive interface elements such as buttons should be large enough, have enough spacing around itself so that they do not overlap with other interactive elements.
#### Color and Contrast
Contrast ratio is the ratio of luminance between the foreground color (such as text) and the background color. For text and images, aim for a large contrast ratio of 7:1 and for larger text (over 18 point or 14 point bold), aim for at least 4.5:1.
Chrome Devtools has an Accessibility audit feature that can flag the contrast issues on your page.
Color should not be used as the sole method of conveying content or distinguishing visual elements, such as only changing the `border-color` of `<input>` fields that have error to red. These changes will not be obvious/visible to people with color blindness. An error message below the field will be helpful.
Some users might be using a High Contrast mode which allows a user to invert the background and foreground colors to read text better. Ensure that your page also looks fine on High Contrast mode which you can simulate with a [Chrome High Contrast extension](https://chrome.google.com/webstore/detail/high-contrast/djcfdncoelnlbldjfhinnjlhdjlikmph?hl=en).
#### Assessing Impact of Accessibility Issues
Fixing accessibility issues is like fixing bugs; it is best looked at through the lens of impact. How can you have the most impact on users with the least amount of effort?
- How frequent is this piece of UI used? Is it part of a critical flow?
- How badly does this accessibility issue affect your users?
- How expensive is it going to cost to fix?
###### References
- https://www.udacity.com/course/web-accessibility--ud891

@ -1,59 +0,0 @@
Browser
==
## Glossary
- **BOM** - The Browser Object Model (BOM) is a browser-specific convention referring to all the objects exposed by the web browser. The `window` object is one of them.
- **CSSOM** - CSS Object Model.
- **DOM** - The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML, and XML documents.
- **Reflow** - When the changes affect document contents or structure, or element position, a reflow (or relayout) happens.
- **Repaint** - When changing element styles which don't affect the element's position on a page (such as `background-color`, `border-color`, `visibility`), the browser just repaints the element again with the new styles applied (that means a "repaint" or "restyle" is happening).
- **Composite** - TODO
## Rendering
High level flow of how browsers render a webpage:
1. DOM
- The DOM (Document Object Model) is formed from the HTML that is received from a server.
- Characters -> Tokens -> Nodes -> DOM.
- DOM construction is incremental.
- CSS and JS are requested as the respective `<link>` and `<script>` tags are encountered.
1. CSSOM
- Styles are loaded and parsed, forming the CSSOM (CSS Object Model).
- Characters -> Tokens -> Nodes -> CSSOM.
- CSSOM construction is not incremental.
- Browser blocks page rendering until it receives and processes all the CSS.
- CSS is render blocking.
1. Render Tree
- On top of DOM and CSSOM, a render tree is created, which is a set of objects to be rendered. Render tree reflects the DOM structure except for invisible elements (like the <head> tag or elements that have `display: none`; set). Each text string is represented in the rendering tree as a separate renderer. Each of the rendering objects contains its corresponding DOM object (or a text block) plus the calculated styles. In other words, the render tree describes the visual representation of a DOM.
1. Layout
- For each render tree element, its coordinates are calculated, which is called "layout". Browsers use a flow method which only required one pass to layout all the elements (tables require more than one pass).
1. Painting
- Finally, this gets actually displayed in a browser window, a process called "painting".
###### References
- http://taligarsiel.com/Projects/howbrowserswork1.htm
- https://medium.freecodecamp.org/its-not-dark-magic-pulling-back-the-curtains-from-your-stylesheets-c8d677fa21b2
## Repaint
When changing element styles which don't affect the element's position on a page (such as `background-color`, `border-color`, `visibility`), the browser just repaints the element again with the new styles applied (that means a "repaint" or "restyle" is happening).
## Reflow
When the changes affect document contents or structure, or element position, a reflow (or relayout) happens. These changes are usually triggered by:
- DOM manipulation (element addition, deletion, altering, or changing element order)
- Contents changes, including text changes in form fields
- Calculation or altering of CSS properties
- Adding or removing style sheets
- Changing the "class" attribute
- Browser window manipulation (resizing, scrolling); Pseudo-class activation (`:hover`)
#### References
- [How Browsers Work](http://taligarsiel.com/Projects/howbrowserswork1.htm)
- [What Every Frontend Developer Should Know About Webpage Rendering](http://frontendbabel.info/articles/webpage-rendering-101/)
- [Rendering: repaint, reflow/relayout, restyle](http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/)
- [Building the DOM faster: speculative parsing, async, defer and preload](https://hacks.mozilla.org/2017/09/building-the-dom-faster-speculative-parsing-async-defer-and-preload/)

@ -1,14 +0,0 @@
Caching
==
WIP.
## Glossary
- **Cookies**
#### References
- [A Tale of Four Caches](https://calendar.perfplanet.com/2016/a-tale-of-four-caches/)
- [Web Caching Basics: Terminology, HTTP Headers, and Caching Strategies](https://www.digitalocean.com/community/tutorials/web-caching-basics-terminology-http-headers-and-caching-strategies)
- [This browser tweak saved 60% of requests to Facebook](https://code.facebook.com/posts/557147474482256/this-browser-tweak-saved-60-of-requests-to-facebook/)

@ -1,34 +0,0 @@
CSS
==
CSS (Cascading Style Sheets) are rules to describe how your HTML elements look. Writing good CSS is hard. It usually takes many years of experience and frustration of shooting yourself in the foot before one is able to write maintainable and scalable CSS. CSS, having a global namespace, is fundamentally designed for web documents, and not really for web apps that favor a components architecture. Hence, experienced front end developers have designed methodologies to guide people on how to write organized CSS for complex projects, such as using [SMACSS](https://smacss.com/), [BEM](http://getbem.com/), [SUIT CSS](http://suitcss.github.io/), etc.
However, the encapsulation of styles that these methodologies bring about are artificially enforced by conventions and guidelines. They break the moment developers do not follow them.
As you might have realized by now, the front end ecosystem is saturated with tools, and unsurprisingly, tools have been invented to [partially solve some of the problems](https://speakerdeck.com/vjeux/react-css-in-js) with writing CSS at scale. "At scale" means that many developers are working on the same large project and touching the same stylesheets. There is no community-agreed approach on writing [CSS in JS](https://github.com/MicheleBertoli/css-in-js) at the moment, and we are hoping that one day a winner would emerge, just like Redux did, among all the Flux implementations. For now, I would recommend [CSS Modules](https://github.com/css-modules/css-modules). CSS modules is an improvement over existing CSS that aims to fix the problem of global namespace in CSS; it enables you to write styles that are local by default and encapsulated to your component. This feature is achieved via tooling. With CSS modules, large teams can write modular and reusable CSS without fear of conflict or overriding other parts of the app. However, at the end of the day, CSS modules are still being compiled into normal globally-namespaced CSS that browsers recognize, and it is still important to learn and understand how raw CSS works.
If you are a total beginner to CSS, Codecademy's [HTML & CSS course](https://www.codecademy.com/learn/learn-html-css) will be a good introduction to you. Next, read up on the [Sass preprocessor](http://sass-lang.com/), an extension of the CSS language which adds syntactic improvements and encourages style reusability. Study the CSS methodologies mentioned above, and lastly, CSS modules.
## Glossary
- [**Box Model**](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model) - The CSS box model describes the rectangular boxes that are generated for elements in the document tree and laid out according to the visual formatting model. Each box has a content area (e.g. text, an image, etc.) and optional surrounding padding, border, and margin areas.
- [**Specificity**](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity) - Specificity is how browsers decide which CSS property values are the most relevant to an element and, will therefore be applied. It is a weight that is applied to a given CSS declaration, determined by the number of each selector type in the matching selector.
- When multiple declarations have equal specificity, the last declaration found in the CSS is applied to the element. It only applies when the same element is targeted by multiple declarations. As per CSS rules, directly targeted elements will always take precedence over rules which an element inherits from its ancestor.
- Typically used in type selectors/pseduo elements (`h1`, `div`, `:before`), class/attribute selectors (`.btn`, `[type="radio"]`), pseudo-classes (`:hover`) and ID selectors (`#someElement`).
- Inline styles added to an element always overwrite any styles in external stylesheets, and thus can be thought of as having the highest specificity.
- When an important rule (`!important`) is used on a style declaration, this declaration overrides any other declarations. Try to avoid using `!important`, as it breaks the natural cascading in the stylesheets. Always look for a way to use specificity before even considering `!important`, and only use !important on page-specific CSS that overrides foreign CSS (from external libraries, like Bootstrap).
- [**Positioning**](https://developer.mozilla.org/en-US/docs/Web/CSS/position) - The position CSS property determines how an element will be positioned in a document. The `top`, `right`, `bottom`, and `left` properties would later determine the final location of said positioned element.
- Initial value: `static`
- Values that are frequently used: `relative`, `absolute`, `fixed`, `sticky`
- [**Floats**](https://developer.mozilla.org/en-US/docs/Web/CSS/float) - The `float` CSS property determines where an element should be placed - along the left or right side of its container. This allows text and inline elements to wrap around it. Also note, the element would be removed from the normal *flow* of the web page, though still remaining a part of the flow (in contrast to `position: absolute`). For an element to be `float`, it's value must not be `none`.
- Initial value: `none`
- Values that are frequently used: `left`, `right`, `inline-start`, `inline-end`.
- Additional Notes: Usually, there would be cases that you may want to move an item below any floated elements. E.g, you may want some elements like your paragraphs to remain adjacent to floats, but force headings and footers to be on their own line. See [`clear` attribute](https://developer.mozilla.org/en-US/docs/Web/CSS/clear) for more examples
## Writing CSS without Side Effects
TODO
###### References
- https://philipwalton.com/articles/side-effects-in-css/

@ -1,14 +0,0 @@
Design Questions
==
## Autocomplete Widget
Talk me through a full stack implementation of an autocomplete widget. A user can type text into it, and get back results from a server.
- How would you design a frontend to support the following features:
- Fetch data from a backend API
- Render results as a tree (items can have parents/children - it's not just a flat list)
- Support for checkbox, radio button, icon, and regular list items - items come in many forms
- What does the component's API look like?
- What does the backend API look like?
- What perf considerations are there for complete-as-you-type behavior? Are there any edge cases (for example, if the user types fast and the network is slow)?
- How would you design the network stack and backend in support of fast performance: how do your client/server communicate? How is your data stored on the backend? How do these approaches scale to lots of data and lots of clients?

@ -1,102 +0,0 @@
DOM
==
## Glossary
- **Event Delegation** - Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future.
## Node API
Here's a list of the essential and more common DOM `Node` APIs. It is important to know how to traverse and manipulate the DOM in vanilla JS without jQuery.
**Properties**
- `Node.childNodes` - Returns a live `NodeList` containing all the children of this node. `NodeList` being live means that if the children of the Node change, the `NodeList` object is automatically updated.
- `Node.firstChild`
- `Node.lastChild`
- `Node.nextSibling` - Returns a `Node` representing the next node in the tree, or `null` if there isn't such a node.
- `Node.nodeName` - `DIV`, `SPAN`, etc. Note that it is in upper case in HTML documents, and has the same value as `Element.tagName`.
- `Node.parentNode` - Returns a `Node` that is the parent of this node. If there is no such node, like if this node is the top of the tree or if it doesn't participate in a tree, this property returns `null`.
- `Node.parentElement` - Returns an `Element` that is the parent of this node. If the node has no parent, or if that parent is not an `Element`, this property returns `null`.
- `Node.previousSibling` - Returns a `Node` representing the previous node in the tree, or `null` if there isn't such a node.
- `Node.textContent` - Returns / Sets the textual content of an element and all its descendants.
**Methods**
- `Node.appendChild(node)` - Adds the specified `node` argument as the last child to the current node. If the argument referenced an existing node on the DOM tree, the node will be detached from its current position and attached at the new position.
- `Node.cloneNode(node)` - Clone a `Node`, and optionally, all of its contents. By default, it clones the content of the node.
- `Node.contains(node)` - Returns a `Boolean` value indicating whether a node is a descendant of a given node or not.
- `Node.hasChildNodes()` - Returns a `Boolean` indicating if the element has any child nodes, or not.
- `Node.insertBefore(newNode, referenceNode)` - Inserts the first `Node` before the reference node as a child of the current node. If `referenceNode` is `null`, the `newNode` is inserted at the end of the list of child nodes.
- `Node.removeChild(node)` - Removes a child node from the current element, which must be a child of the current node.
- `Node.replaceChild(newChild, oldChild)` - Replaces one child node of the specified node with another node.
## Element API
Here's a list of the essential and more common DOM `Element` APIs. It is important to know how to traverse and manipulate the DOM in vanilla JS without jQuery.
**Properties**
- `Element.attributes` - Returns a `NamedNodeMap` object containing the assigned attributes of the corresponding HTML element.
- `Element.classList` - Returns a `DOMTokenList` containing the list of class attributes.
- `DOMTokenList.add(String [, String])` - Add specified class values. If these classes already exist in attribute of the element, they are ignored.
- `DOMTokenList.remove(String [, String])` - Remove specified class values.
- `DOMTokenList.toggle(String [, force])` - Toggle specified class value. If second argument is present and evaluates to `true`, add the class value, else remove it.
- `DOMTokenList.contains(String)` - Checks if specified class value exists in class attribute of the element.
- `Element.className` - A `DOMString` representing the class of the element.
- `Element.id`
- `Element.innerHTML` - Returns a `DOMString` representing the markup of the element's content or parse the content string and assigns the resulting nodes as children of the element.
- `Element.tagName` - `DIV`, `SPAN`, etc. Note that it is in upper case in HTML documents, and has the same value as `Node.nodeName`.
**Methods**
- `EventTarget.addEventListener(type, callback, options)` - Registers an event handler to a specific event type on the element. Read up more on the `options` [here](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener).
- `EventTarget.removeEventListener(type, callback, options)` - Removes an event listener from the element. Read up more on the `options` [here](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener).
- `Element.closest(selectors)` - Returns the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter. If there isn't such an ancestor, it returns `null`.
- `Element.getElementsByClassName(classNames)`- Returns a live `HTMLCollection` that contains all descendants of the current element that possess the list of classes given in the parameter.
- `Element.getElementsByTagName(tagName)` - Returns a live `HTMLCollection` containing all descendant elements, of a particular tag name, from the current element.
- `Element.querySelector(selectors)` - Returns the first `Node` which matches the specified selector string relative to the element.
- `Element.querySelectorAll(selectors)` - Returns a `NodeList` of nodes which match the specified selector string relative to the element.
- `ChildNode.remove()` - Removes the element from the children list of its parent. TODO: Check whether it's `Element` or `ChildNode`.
- `Element.setAttribute(attrName, value)` - Sets the value of a named attribute of the current node.
- `Element.removeAttribute(attrName)` - Removes the named attribute from the current node.
## Document API
- `document.getElementById(id)` - An Element object, or null if an element with the specified ID is not in the document.
## Window/Document Events
- `document.addEventListener('DOMContentLoaded', callback)`
- The `DOMContentLoaded` event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. Similar to `jQuery.ready()` but different because `$.ready` will execute immediately if the `DOMContentLoaded` event has already fired.
- This corresponds to `document.readyState === 'interactive'`.
- `window.onload = function() {}`
- `window`'s `load` event is only fired after the DOM and all assets have loaded.
- This corresponds to `document.readyState === 'complete'`.
## Questions
**What's the difference between `Node.children` and `Node.childNodes`?**
`Node.children` returns a live `HTMLCollection` of the child `elements` of `Node`. `Node.childNodes` returns a `NodeList`, an ordered collection of DOM nodes that are children of the current `Element`. `childNodes` includes all child nodes, including non-element nodes like text and comment nodes. To get a collection of only elements, use `Node.children` instead.
**What's the difference between `NodeList` and `HTMLCollection`?**
A `NodeList` can contain any node type, but an `HTMLCollection` is supposed to only contain `Element` nodes. `HTMLCollection` is always live and is a superset of `NodeList`. `NodeList` need not be live.
**How do you convert an `HTMLCollection` or `NodeList` into an array?**
```js
const nodelist = document.querySelectorAll('div');
// Array.from
const divArray = Array.from(nodelist);
// Array.prototype.slice
const divArray2 = Array.prototype.slice.call(nodelist); // or .apply
// ES2015 Spread
const divArray3 = [...nodeList];
```
## References
- https://developer.mozilla.org/en-US/docs/Web/API/Node
- https://developer.mozilla.org/en-US/docs/Web/API/Element

@ -1,18 +0,0 @@
HTML
==
HTML (Hypertext Markup Language) is the structure that all websites are built on. Anyone working on websites and webapps should have a basic understanding of HTML at the very least. A helpful analogy for understanding the importance of HTML is the house scenario. When building a new house, the process can be split into a few key areas; structure (HTML), aesthetics (CSS) and furniture (Content). The HTML is your basic page structure, without the structure, you cannot change how it looks using CSS, or what content is on the page.
## Glossary
- **Doctype**
## Deprecated Tags
There are a number of tags from past versions of HTML that have become deprecated over time. This means that while they are no longer considered valid elements, most browsers should still be able to read and render them.
## Script Loading
- `<script>` - HTML parsing is blocked, the script is fetched and executed immediately, HTML parsing resumes after the script is executed.
- `<script async>` - The script will be fetched in parallel to HTML parsing and executed as soon as it is available (potentially before HTML parsing completes). Use `async` when the script is independent of any other scripts on the page, for example analytics.
- `<script defer>` - The script will be fetched in parallel to HTML parsing and executed when the page has finished parsing. If there are multiple of them, each deferred script is executed in the order they were encoun­tered in the document.

File diff suppressed because it is too large Load Diff

@ -1,108 +0,0 @@
JavaScript
==
WIP.
## Contents
- [Glossary](#glossary)
- [Core Language](#core-language)
- [Design Patterns](#design-patterns)
- [Strict Mode](#strict-mode)
## Glossary
- **Closure** - "Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope." - [YDKJS](https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch5.md)
- **Event Loop** - The event loop is a single-threaded loop that monitors the call stack and checks if there is any work to be done in the message queue. If the call stack is empty and there are callback functions in the message queue, a message is dequeued and pushed onto the call stack to be executed.
- **Hoisting** - "Wherever a var appears inside a scope, that declaration is taken to belong to the entire scope and accessible everywhere throughout." - [YDKJS](https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch2.md#hoisting)
- **Promise** - "The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value." - [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
- Promises can contain an immediate value.
- **Prototype** - TBD
- **This** - The `this` keyword does not refer to the function in which `this` is used or that function's scope. Javascript uses [4 rules](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md#determining-this) to determine if `this` will reference an arbitrary object, *undefined* or the *global* object inside a particular function call.
## Core Language
### Variables
- Reference: [Types and Grammar](https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch1.md)
- Types
- Scopes
- [Coercion](https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch2.md#coercion)
### Functions
- Reference: [this & Object Prototypes](https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch3.md)
- Declaration vs Expression
- Closures
- `.call`, `.apply` and `.bind`
- Currying
- Arrow functions and lexical this
### Prototypes and Objects
- Reference: [this & Object Prototypes](https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/README.md#you-dont-know-js-scope--closures)
- Prototype chain
- `this` keyword
- https://rainsoft.io/gentle-explanation-of-this-in-javascript/
- https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3
- Classes
- Methods
- Use non-arrow functions for methods that will be called using the `object.method()` syntax because you need the value of `this` to point to the instance itself.
### Async
- Reference: [Async and Peformance](https://github.com/getify/You-Dont-Know-JS/blob/master/async%20&%20performance/README.md#you-dont-know-js-async--performance)
- `setTimeout`, `setInterval` and event loop
- [setImmediate() vs nextTick() vs setTimeout(fn,0)](http://voidcanvas.com/setimmediate-vs-nexttick-vs-settimeout/)
- Event Loop
- Debounce and Throttle
- Throttling enforces a maximum number of times a function can be called over time.
- Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called.
- https://css-tricks.com/debouncing-throttling-explained-examples/
- Callbacks
- [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
- [Async](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) and [Await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) in ES7
**Reference**
- https://www.vikingcodeschool.com/falling-in-love-with-javascript/the-javascript-event-loop
## Design Patterns
- https://addyosmani.com/resources/essentialjsdesignpatterns/book/
## Strict Mode
1. Strict mode eliminates some JavaScript silent errors by changing them to throw errors.
1. Strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations. Strict mode code can sometimes be made to run faster than identical code that's not strict mode.
1. Strict mode prohibits some syntax likely to be defined in future versions of ECMAScript.
**Converting Mistakes into Errors**
- Prevent accidental creation of global variables.
- Makes assignments which would otherwise silently fail throw an exception.
- Makes attempts to delete undeletable properties throw errors.
- Requires that all properties named in an object literal be unique. Duplicate property names are a syntax error in strict mode.
- Requires that function parameter names be unique. In normal code the last duplicated argument hides previous identically-named arguments.
- Forbids setting properties on primitive values in ES6. Without strict mode, setting properties is simply ignored (no-op), with strict mode, however, a `TypeError` is thrown.
**Simplifying Variable Uses**
- Prohibits `with`.
- `eval` of strict mode code does not introduce new variables into the surrounding scope.
- Forbids deleting plain variables. `delete` name in strict mode is a syntax error: `var x; delete x; // !!! syntax error`.
**Paving the way for future ECMAScript versions**
- Future ECMAScript versions will likely introduce new syntax, and strict mode in ECMAScript 5 applies some restrictions to ease the transition. It will be easier to make some changes if the foundations of those changes are prohibited in strict mode.
- First, in strict mode a short list of identifiers become reserved keywords. These words are `implements`, `interface`, `let`, `package`, `private`, `protected`, `public`, `static`, and `yield`. In strict mode, then, you can't name or use variables or arguments with these names.
- Second, strict mode prohibits function statements not at the top level of a script or function.
## Transpilation: TBD
## Useful Links
- https://medium.com/javascript-scene/10-interview-questions-every-javascript-developer-should-know-6fa6bdf5ad95#.l2n8icwl4
- https://github.com/mbeaudru/modern-js-cheatsheet
- [Functional Programming in Javascript - Javascript Allonge](https://leanpub.com/javascriptallongesix/read)
- [Dr. Frisby's Mostly Adequate Guide to Functional Programming](https://drboolean.gitbooks.io/mostly-adequate-guide/content/)

@ -1,11 +0,0 @@
Networking
==
WIP.
## Glossary
- **JSON**
- **RPC**
- **HTTP**
- **HTTP/2**

@ -1,66 +0,0 @@
Performance
==
WIP.
## Glossary
- **Critical Rendering Path** -
- `requestAnimationFrame`
## General Strategies
1. Minimize Bytes.
1. Reduce critical resources.
1. Reduce CRP length. TODO: Explain what CRP length is.
## Loading
- Minify, Compress, Cache assets.
- Browsers have a [preloader](https://andydavies.me/blog/2013/10/22/how-the-browser-pre-loader-makes-pages-load-faster/) to load assets ahead of time.
## Rendering
- Remove whitespace and comments from HTML/CSS/JS file via minification.
- CSS
- CSS blocks rendering AND JavaScript execution.
- Split up CSS for fewer rendering blocking CSS stylesheets by using media attributes.
- Download only the necessary CSS before the browser can start to render.
- https://developers.google.com/web/fundamentals/design-and-ui/responsive/#css-media-queries
- Use Simpler selectors.
- JavaScript
- JS blocks HTML parsing. If the script is external, it will have to be downloaded first. This incurs latency in network and execution.
- Shift `<script>` tags to the bottom.
- Async:
- Scripts that don't modify the DOM or CSSOM can use the `async` attribute to tell the browser not to block DOM parsing and does not need to wait for the CSSOM to be ready.
- Defer JavaScript execution:
- There is also a `defer` attribute available. The difference is that with `defer`, the script waits to execute until after the document has been parsed, whereas `async` lets the script run in the background while the document is being parsed.
- Use web workers for long running operations to move into a web worker thread.
- Use `requestAnimationFrame`
###### References
- https://bitsofco.de/understanding-the-critical-rendering-path/
## Measuring
- [Navigation Timing API](https://developer.mozilla.org/en/docs/Web/API/Navigation_timing_API) is a JavaScript API for accurately measuring performance on the web. The API provides a simple way to get accurate and detailed timing statistics natively for page navigation and load events.
- `performance.timing`: An object with the timestamps of the various events on the page. Some uses:
- Network latency: `responseEnd` - `fetchStart`.
- The time taken for page load once the page is received from the server: `loadEventEnd` - `responseEnd`.
- The whole process of navigation and page load: `loadEventEnd` - `navigationStart`.
## Tools
- Yahoo YSlow
- Google PageSpeed Insights
- WebPageTest
- Sitespeed.io
- Google Lighthouse
## Web Performance Rules
- https://developers.google.com/web/fundamentals/performance/critical-rendering-path/measure-crp
- http://stevesouders.com/hpws/rules.php
- https://developer.yahoo.com/performance/rules.html
- https://browserdiet.com/en/

@ -1,110 +0,0 @@
Security
==
## Glossary
- **CORS** - Cross-Origin Resource Sharing (CORS).
- **CSRF** - Cross-Site request forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated.
- **XSS** - Cross-site scripting (XSS).
## CORS
The same-origin policy protects users by disallowing websites to retrieve information from other websites of different origins. An origin is the triple {protocol, host, port}. Two resources are considered to be of the same origin if and only if all these values are exactly the same.
Cross-Origin Resource Sharing allows relaxing of the same-origin policy. CORS defines a way in which a browser and server can interact to determine whether or not it is safe to allow the cross-origin request.
This standard extends HTTP with a new `Origin` request header and `Access-Control-Allow-Origin` and `Access-Control-Allow-Methods` response headers. It allows servers to use a header to explicitly list origins and HTTP methods that may request a file or to use a wildcard and allow a file to be requested by any site. `XMLHttpRequest`s to a target origin from a different source origin will be blocked if the server did not allow CORS for source origin.
## CSRF
XSS vulnerabilities allow attackers to bypass essentially all CSRF preventions.
#### Protection
- Verifying Same Origin with Standard Headers
- There are two steps to this check:
1. Determining the origin the request is coming from (source origin).
2. Determining the origin the request is going to (target origin).
- Examine the `Origin`, `Referer` and `Host` Header values.
- Synchronizer Tokens
- The CSRF token is added as a hidden field for forms or within the URL.
- Characteristics of a CSRF Token
- Unique per user session
- Large random value
- Generated by a cryptographically secure random number generator
- The server rejects the requested action if the CSRF token fails validation.
- Double Cookie
- When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. The site should require every form submission to include this pseudorandom value as a form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An attacker cannot read any data sent from the server or modify cookie values, per the same-origin policy. This means that while an attacker can send any value he wants with the form, he will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the pseudorandom value.
- The advantage of this approach is that it requires no server state; you simply set the cookie value once, then every HTTP POST checks to ensure that one of the submitted <input> values contains the exact same cookie value. Any difference between the two means a possible XSRF attack.
- Cookie-to-Header Token
- On login, the web application sets a cookie containing a random token that remains the same for the whole user session
- `Set-Cookie: Csrf-token=i8XNjC4b8KVok4uw5RftR38Wgp2BFwql; expires=Thu, 23-Jul-2015 10:25:33 GMT; Max-Age=31449600; Path=/`
- JavaScript operating on the client side reads its value and copies it into a custom HTTP header sent with each transactional request
- `X-Csrf-Token: i8XNjC4b8KVok4uw5RftR38Wgp2BFwql`
- The server validates presence and integrity of the token.
- Security of this technique is based on the assumption that only JavaScript running within the same origin will be able to read the cookie's value.
- JavaScript running from a rogue file or email will not be able to read it and copy into the custom header. Even though the `csrf-token` cookie will be automatically sent with the rogue request, the server will be still expecting a valid `X-Csrf-Token` header.
- Use of Custom Request Headers
- An alternate defense which is particularly well suited for AJAX endpoints is the use of a custom request header. This defense relies on the same-origin policy (SOP) restriction that only JavaScript can be used to add a custom header, and only within its origin. By default, browsers don't allow JavaScript to make cross origin requests. Such a header can be `X-Requested-With: XMLHttpRequest`.
- If this is the case for your system, you can simply verify the presence of this header and value on all your server side AJAX endpoints in order to protect against CSRF attacks. This approach has the double advantage of usually requiring no UI changes and not introducing any server side state, which is particularly attractive to REST services. You can always add your own custom header and value if that is preferred.
- Require user interaction
- Require a re-authentication, using a one-time token, or requiring users to complete a captcha.
###### References
- [OWASP CSRF](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF))
## HTTPS
HTTPS is HTTP over SSL/TLS. Servers and clients still speak exactly the same HTTP to each other, but over a secure SSL connection that encrypts and decrypts their requests and responses. The SSL layer has 2 main purposes:
1. Verifying that you are talking directly to the server that you think you are talking to.
1. Ensuring that only the server can read what you send it and only you can read what it sends back.
#### TLS Handshake
// TODO. Crosscheck and add in more details.
1. The client computer sends a `ClientHello` message to the server with its Transport Layer Security (TLS) version, list of cipher algorithms and compression methods available.
1. The server replies with a `ServerHello` message to the client with the TLS version, selected cipher, selected compression methods and the server's public certificate signed by a CA (Certificate Authority). The certificate contains a public key that will be used by the client to encrypt the rest of the handshake until a symmetric key can be agreed upon.
1. The client verifies the server digital certificate against its list of trusted CAs. If trust can be established based on the CA, the client generates a string of pseudo-random bytes and encrypts this with the server's public key. These random bytes can be used to determine the symmetric key.
1. The server decrypts the random bytes using its private key and uses these bytes to generate its own copy of the symmetric master key.
1. The client sends a `Finished` message to the server, encrypting a hash of the transmission up to this point with the symmetric key.
1. The server generates its own hash, and then decrypts the client-sent hash to verify that it matches. If it does, it sends its own `Finished` message to the client, also encrypted with the symmetric key.
1. From now on the TLS session transmits the application (HTTP) data encrypted with the agreed symmetric key.
#### Downsides of HTTPS
- TLS handshake computational and latency overhead.
- Encryption and decryption requires more computation power and bandwidth.
###### References
- https://blog.hartleybrody.com/https-certificates/
- https://github.com/alex/what-happens-when#tls-handshake
- http://robertheaton.com/2014/03/27/how-does-https-actually-work/
## XSS
XSS vulnerabilities allow attackers to bypass essentially all CSRF preventions.
```js
const name = "<img src='x' onerror='alert(1)'>";
el.innerHTML = name;
```
http://shebang.brandonmintern.com/foolproof-html-escaping-in-javascript/
## Session hijacking
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
- https://www.nczonline.net/blog/2009/05/12/cookies-and-security/
## Framebusting
https://seclab.stanford.edu/websec/framebusting/framebust.pdf
## API
https://github.com/shieldfy/API-Security-Checklist

@ -1,56 +0,0 @@
Widgets
==
Here are some commonly seen widgets/components and the considerations we should take into account when designing them.
### Autocomplete
Also known as typeahead box.
#### UX
- Type a minimum number of characters (typically two) for the results to be displayed. This is because short search terms can result in too many matches and irrelevant results may be returned.
- Number of query suggestions should be kept short and scrollbars should be avoided. Shorter list of results are more manageable and reduces the cognitive load on the user. If you have scrollbars it probably means you are displaying too many results!
- Highlight the non-search terms (suggested terms) in the results. This helps the user differentiate the autocomplete suggestions, make it easier to compare.
- Support keyboard shortcuts: Up/down to navigate and enter to search.
- Show a history of recent searches.
- Use placeholder text in the input field to educate users, such as "Type to view suggestions".
#### Performance
- Use windowing/virtual lists when the search results is too long.
- Debounce user input and only search when user stops typing for some time (usually 300ms).
###### References
- https://baymard.com/blog/autocomplete-design
### Carousel
#### UX
- Consider preloading a few images to the left/right of the displayed image during idle time so that as the user navigates, he does not have to wait for the image to be downloaded.
- Allow left/right keyboard navigation of the carousel.
#### Performance
- Lazy load the images. Only load those that the user has a high likelihood of viewing - Current image and a few to the left and right.
### Dropdown
- Dropdowns that are displayed on hover are not mobile friendly as there is no hover event on mobile.
- Dropdown positioning can differ based on position of element on screen. If the element is near the edge and the displayed dropdown will be obscured outside of the viewport, the position of the dropdown can and should be changed.
- If the height of the dropdown is too long, it may extend outside of the screen. Be sure to make the dropdown contents scrollable by setting a `max-height`.
### Modal
- Modals can usually be dismissed by clicking on the backdrop. If the user interacts with the modal content by clicking on it, the backdrop might also receive the click event and be dismissed as a result.
###### References
- https://css-tricks.com/dangers-stopping-event-propagation/
### Tooltip
- Tooltips that are displayed on hover are not mobile friendly as there is no hover event on mobile.
- Tooltip positioning can differ based on position of element on screen. If the element is near the edge and the displayed tooltip will be obscured outside of the viewport, the position of the tooltip can and should be changed.
Loading…
Cancel
Save