Web Fragments



SGML (Standard Generalized Markup Language), created by IBM in 1969, standarded by ISO in 1986.

cookie - identify users.

Storage Size

  • cookie <= 4kB
  • sessionStorage & localStorage >= 5MB

Period of Validity

  • cookie - valid before period of validity;
  • localStorage - permanent;
  • sessionStorage - be deleted when browser closed.

Web Standards

What are Web Standards?1

Web standards are rules and guidelines established by the World Wide Web Consortium (W3C) developed to promote consistency in the design code which makes up a web page. Without getting technical, simply it’s the guideline for the mark-up language which determines how a web page display in a vistor’s browser window.


SEO2 (Search Engine Optimization) is the process of making a website more visible in search results, also termed improving search rankings.

Search engines crawl the web, following links from page to page, and index the content found. When you search, the search engine displays the indexed content. Crawlers follow rules. If you follow those rules closely when doing SEO for a website, you give the site the best chances of showing up among the first results, increasing traffic and possibly revenue (for ecommerce and ads).

Search engines give some guidelines for SEO, but big search engines keep result ranking as trade secret. SEO combines official search engine guidelines, empirical knowledge, and theoretical knowledge from science papers or patents.

SEO methods fall into three broad classes:

  • technical - Tag the content using semantic HTML. When exploring the website, crawlers should only find the content you want indexed;
  • copywriting - Write content using your visitors’ vocabulary. Use text as well as images so that crawlers can understand the subject;
  • popolarity - You get most traffic when other established sites link to your site.

And you can offer your site to SEO via SEO Login Lists :)

Browser Engine



!important > id > class > tag

Selector Demo Description
el el
el+el div+p
[attribute~=value] [title~=flower] select title attributes included “flower”
[attribute1=value] [lang1=en] select lang attributes started with “en”
:hover a:hover
input:focus select elements focused
:first-letter p:first-letter
:first-line p:first-line
:first-child p:first-child

‘s parent’s first child element is

:last-child p:last-child
:only-child p:only-child

‘s parent only has one element is

:nth-child(n) p:nth-child(2)

‘s parent’s second element is

:nth-last-child(n) p:nth-last-child(2)
:first-of-type p:first-of-type

‘s parent’s first


:only-of-type p:only-of-type

‘s parent only has one


:nth-of-type(n) p:nth-of-type(2)

‘s parent’s second


:empty p:empty

has no child-element (included text-node)

:before p:before insert ctx before every


:nnt(selector) :not(p) non-



for…in and for…of

Both for.in and for.of statements iterate over something. The main difference between them is in what they iterate over.

The for.in statement iterates over the enumerable properties of an object, in an arbitray order.

The for.of statement iterates over values that the iterable object defines to be iterated over.

Here is an example shows the difference between a for.of loop and a for.in loop when used with an Array.

Object.prototype.objCustom = function() {};
Array.prototype.arrCustom = function() {};

let iterable = [3, 5, 7];
iterable.foo = 'hello';

// for.in
for (let i in iterable) {
    console.log(i);        // 0, 1, 2, 'foo', 'arrCustom', 'objCustom'

for (let i in iterable) {
    if (iterable.hasOwnProperty(i)) {
    console.log(i);        // 0, 1, 2, 'foo'

// for.of
for (let i of iterable) {
    console.log(i);        // 3, 5, 7

Via above, note:

  • for.in get index (i.e. key)
  • for.of get value
  • for.in defaultly loop every key/index it can find.

So we often use for.of to loop Array, while for.in to loop Object.

Prototype and Prototype Chain

Prototype and Prototype Chain3





The XHR (XMLHttpRequest) API is the core of AJaX (Asynchronous JavaScript and XML).


[XHR Object]

Use XHR objects to interact with servers, you can retrieve data from a URL without having to do a full page refresh. This enable a Web page to update just part of a page without disrupting what the user is doing.


XMLHttpRequest() - The constructor initializes an XMLHttpRequest. A new XHR object must be prepared by at least calling open() to initialize itself before calling send() to send the request to the server.

// Create an XHR object
const xhr = new XMLHttpRequest();

// GET
xhr.open('GET', 'ajax_info.txt', true);

xhr.open('POST', '/try/ajax/demo_post.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');


This interface also inherits properties of XMLHttpRequestEventTarget and of EventTarget.


Property Description
onreadystatechange An EventHandler that is called whenever the readyState attribute changes.
readyState Read only. Returns an unsigned short, the state of the request.
responseText Read only. Returns a DOMString that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.
responseXML Read only. Returns a Document containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in workers.

To readyState, here are its states:

Value State Description
0 UNSENT Client has been created. open() not called yet
1 OPENED open() has been called
2 HEADERSRECEIVED send() has been called, and headers and status are available
3 LOADING Downloading; responseText holds partial data.
4 DONE The operation is complete.


Method Description
setRequestHeader(header, value) Sets the value of an HTTP request header. It must be called after open(), but before send().
open(method, url, async) Initializes a request. method (HTTP request method), url (resource url), async (ture or false)
send() Sends the request.


Event Related Property Description
abort onabort Fired when a request has been aborted
error onerror Fired when the request encountered an error
load onload Fired when an XHR transaction completes successfully
loadend onloadend Fired when a request has completed, whether successfully (after load) or unsuccessfully (after abort or error)
loadstart onloadstart Fired when a request has started to load data.
progress onprogress Fired periodically when a request receives more data.


The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function. The new keywords does the following things:

  1. Creates a blank, plain JavaScript object;
  2. Links (sets the constructor of) this object to another object;
  3. Passes the newly created object from Step1 as the this context;
  4. Returns this if the function doesn’t return its own object.



Run console.dir(Promise), show like this:


Acturally, Promise is a constructor and its prototype property pointed to a Promise.prototype Object.

To Promise constructor, methods included:

  • Promise.resolve()
  • Promise.reject()
  • Promise.all()
  • Promise.race()

To Promise.prototype object, methods included:

  • Promise.prototype.then()
  • Promise.prototype.catch()
  • Promise.prototype.finally()

A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected;
  • fulfilled: meaning that the operation completed successfully;
  • rejected: meaning that the operation failed.

[Create a Promise]

const myFirstPromise = new Promise((resolve, reject) => {
    // do something asynchronous which eventually calls either
    // .
    //   resove(somevalue);         // fulfilled
    // or
    //   reject('failure reason');  // rejected

Here a specific example – Loading an image with XHR, and you can also see it in action.

Arrow Function

Arrow Function6

When a return statement is used in a function body, the execution of the function is stopped.

  • If specified, a given value is returned to the function caller;
  • If the value is omitted, undefined is returned instead.

An arrow function expression is a syntactically compact alternative to a regular function expression,

  • although without its own bindings to the this, arguments, super, or new.target keywords;
  • arrow function expressions are ill suited as methods, and
  • they cannot be used as constructors.

Two factors influenced the introduction of arrow functions: shorter functions and no existence of this keyword.


The static method Object.defineProperty() :

  • defines a new property directly on an object, or
  • modifies an existing property on an object, and
  • returns the object.

Note: You can call this method directly on the Object constructor rather than on an instance of type Object.


Object.defineProperty(obj, prop, descriptor)

To arguments:

  • obj - The object on which to define the property;
  • prop - The name or Symbol of the property to be defined or modified;
  • descriptor - The descriptor for the property being defined or modified.

To descriptor:

Descriptor Default Description
configurable false true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
enumerable false true if and only if this property shows up during enumberation of the properties on the corresponding object.
writable false true if and only if the value associated with the property may be changed with an assignment operator.
value undefined The value assocated with the property, which can be any valid JavaScript value (number, object, function, etc.)
get undefined A function which serves as a getter for the property, or undefined if there is no getter.
set undefined A function which serves as a setter for the property, or undefined if there is no setter.

A simple example:

const obj = {};

Object.defineProperty(obj, 'prop', {
    value: 42,
    writable: false
obj.prop = 77;            // throws an error in strict mode
console.log(obj.prop);        // 42



Lifecycle Diagram

<div id="app">
  <h1>{{ message }}</h1>

  const vm = new Vue({
    el: '#app',
    data: {
      message: 'Vue Lifecycle Msg'

Please note that hook is just a exact time dot, not a process.

Level Lifecycle Description Status
NEW Init Events & Lifecycle
>el: undefined
>>>>>> beforeCreate >data: undefined
>msg: undefined
CREATE Init injections & reactivity
<el: undefined
<<<<<< Created <data: [object Obejct]
<msg: Vue Lifecycle Msg
1.Has el option?
>NO >>> when vm.$mount(el) is called
2.Has template option?
>YES>>> Compile template into render function
>NO >>> Compile el‘s outerHTML as template
>el: [object HTMLDivElement]
>>>>>> beforeMount >this.$el: <div id="app"><h1>\{\{msg}}</h1></div>
>data: [object Object]
>msg: Vue Lifecycle Msg
MOUNT Create vm.$el and replace el with it
<el: [object HTMLDivElement]
<<<<<< mounted <this.$el: <div id="app"><h1>Vue Lifecycle Msg</h1></div>
<data: [object Object]
<msg: Vue Lifecycle Msg
>>>>>> beforeUpdate when data change
?UPDATE Virtual DOM re-render and patch
<<<<<< updated
>>>>>> beforeDestroy when vm.$destroy() is called
?DESTROY Teardown watchers, child components and event listeners
<<<<<< destroyed
END —— ——


HTML/XML => Nodes => DOM Tree


Here seven node types:

  • Document
  • DocumentType (e.g. doctype tag)
  • Element
  • Attribute
  • Text
  • Comment
  • DocumentFragment

In DOM-tree, except for <html>, others have three relationship:

  • parentNode
  • childNodes
  • sibling


Property Description
nodeType document.nodeType equals Node.Document_NODE eauals 9
‘s nodeName is DIV
nodeValue only text, comment, attribute nodes have text value, others return null
textContent To text, comment, attribute nodes, same as nodeValue , otheres return a connected string contents
nextSibling next first sibling node, or null
parentNode return current node’s parent node
parentElement return current node’s parent node which must be element node, or null
firstChild return current node’s first child-node
childNodes return a NodeList
isConnnected return a boolean, indicates if current node in document
baseURI current site’s URL


Method Description
appendChild() document.body.appendChild(p)
hasChindNodes() return a boolean, indicates if current node has child-nodes
or node.firstChild !== null
or node.childNodes && node.childNodes.length >0
cloneNode() document.querySlector('ul').cloneNode(true); receive a boolean, indicates if clone?
insertBefore() parentNode.insertBefore(newNode, referenceNode);
removeChild() divA.parentNode.removeChild(divA);
replaceChild() parentNode.replaceChild(newChild, oldChild);
contains() document.body.contains(node); return a boolean

HTMLCollection and NodeList

NodeList includes every node types, but HTMLCollection only be HTML element node.


Property & Method Description
length document.querySlectorAll('p').length
forEach() receive a callback, be invoked when loop
item() receive a int number, return its related item
keys(), values(), entries() return a ES6 Inteator object


Property Description
namedItem() receive a string indecating value of id or name , return a related node


document inherits EventTarget , Node and ParentNode.

Here some often-used properties:

Property Description
document.doctype “<!DOCTYPE html>”
document.doctype.name “html”
All return HTMLCollection
document.links all and nodes that set href
document.forms all
document.images all nodes
document.documentURI return path of current document
document.URL same as above, but URL inherits HTMLDocument
document.location eq window.location
document.lastModified return a last-modified-time string
document.title return title of current document
document.hidden return a boolean, indicates a page visibility
document.visibilityState visble hidden prerender unloaded
document.readyState loading interactive complete

Here some used Methods:

Method Description
open() clear contents of current document, ready for document.write()
close() close documents opened
write() before DOMContentLoaded event - append contents; If after - first exec open() i.e. clear all contents, then write new contents
querySlector() receive some CSS Selector (not support pseudo selectors), return a element node. If has serval ones, return the first one. If has none, return null
querySlectorALL() like above, but return a NodeList
getElementsByTagName() return a HTMLCollection
getElementsByClassName() return a HTMLCollection
getElementsByName() return a NodeList of nodes which have name property
getElementById() receive a value of id property, return a pattern node if has
createElement(tagname) create then return a new element node
createTextNode(data) create then return a text node
createAttibute(attrname) create then return a attribute node. And set a value by setAttricute(name, value)
createDocumentFragment() create then return a new documentFragment node
createEvent(type) type - UIEvents, MouseEvents, MutationEvents and HTMLEvents
addEventListener(type, listener, isCapture)
removeEventListener(type, listener, isCapture)


Actually, Element Node Object is a set of diffrent Objects since differnet HTML element has different Constrctor FN.

Property Description
tagName ‘TAGNAME’
dir “ltr” or “rtl”
title hover text description
hidden return a boolean
contentEditable return a string, includes “true”, “false”, “inherit”
isContentEditable return a boolean, indicates if set contentEditable
attributes return an Array-like Object including all attr nodes
className return a string
classList return an Array-like Object
dataset return an Object including all attributes added by data-
innerHTML return a string which equals all HTML CODE included
outerHTML same as above and also included itself
clientHeight, clientWidth
clientLeft, clientTop
scrollHeight, scrollWidth
scrollLeft, scrollTop
offsetHeight, offsetWidth
offsetLeft, offsetTop
children, childElementCount
firstElementChild, lastElementChild
nextElementChild, previousElementSibling

To className & classList:

// HTML => <div class="one two three" id="myDiv"></div>
let div = document.getElementById('myDiv');

// "one two three"

// {
//   0: "one"
//   1: "two"
//   2: "three"
//   length: 3
// }

// Here some methods of classList
div.classList.add('foo', 'bar');
div.classList.toggole('myCssClass'[, boolValue]); // boolValue is 'true', add. or remove
div.classList.toString();    // list to string

More about className and classList:

let foo = document.getElementById('foo');

// add a class
foo.className += 'bold';

// remove a class
foo.className = foo.className.replace(/^blod$/, '');

To dataset:

// <article
//   id="foo"
//   data-columns="3"
//   data-index-number="12314"
//   data-parent="cars">
//   .
// </article>
var article = document.getElementById('foo');
article.dataset.columns // "3"
article.dataset.indexNumber // "12314"
article.dataset.parent // "cars"


JavaScript Script

Here four ways to load JavaScript script:

  • <script> tag embeds code directly;
  • load outter script via <script> tag;
  • event attributes;
  • URL protocol.

[Working Principle]


  1. Downloading & Parsing HTML;
  2. <script> occurs, stop Parsing => JavaScript engine;
  3. Down outter script done, then execute it => Rendering engine;
  4. Go on parsing HTML.

Note that, when a outter script is downloading, Rendering engine stop parsing HTML. Here some ways to slove the problem - DOMContentLoaded or onload , defer, async, or just put it bottom of the page.

// DOMContentLoaded
    document.addEventListener('DOMContentLoaded', (event) => {

// onload
<script src="jquery.min.js" onload="console.log(document.body.innerHTML)"></script>


  1. Downloading & parsing HTML;
  2. defer occurs, keep parsing HTML and start downloading outter scripts;
  3. Parse HTML done, then execute outter scripts.


  1. Downloading & parsing HTML;
  2. async occurs, keep parsing HTML and start downloading outter scripts;
  3. Download outter scripts done, then stop parsing HTML and execute outter scripts;
  4. Exec done, then go on parsing HTML.

Loading scripts Dynamically

['a.js', 'b.js'].forEach(src => {
  let script = document.createElement('script');
  script.scr = src;
  // script.async = false;  // false => load outter scripts in order, true => first download done, first load

If you want set a callback more:

function loadScript(src, done) {
  let script = document.creatElement('script');
  script.src = src;
  script.onload = () => done();
  script.onerror = () => done(new Error('Failed to load script ' + src));

Browser Engine

[Rendering Engine]

Rendering Engine Browser
Gecko Firefox
WebKit Safari
Blink Chrome
Trident IE
EdgeHTML Edge

Here four processes when render a web page:

  1. HTML => DOM, CSS => CSSOM;
  2. DOM & CSSOM => render tree;
  3. Compute layouts of render tree;
  4. Paint render tree to screen.

[JavaScript Engine]

JavaScript Engine Browser
SpiderMonkey Firefox
Nitro/JavaScript Core Safari
V8 Chrome, Chromium
Chakra IE
Carakan Opera

Older Browser

Interpreted language => run

Compiled language => bytecode => run

Here four processes of phrasing JavaScript in older browsers:

  1. JavaScript code (via Lexical analysis) => token;
  2. token (via Syntax parsing) => syntax tree;
  3. syntax tree code (via translator) => bytecode;
  4. bytecode (via bytecode interpreter) => machine code.

Modern Browser

code (via JIT (Just In Time compiler)) => bytecode & inline cache (via Virtual Machine) => machine code

code (via JIT & VM) => machine code.


HTTP (Hypertext Transfer Protocol) is an application-layer protocol which allows the fetching of resources, often based on a TCP/IP layer.




Requests consists of the following elements:

  • An HTTP method, like GET, HEAD, POST, PUT, DELETE or OPTIONS etc.;
  • The path of the resource to fetch;
  • The version of the HTTP protocol;
  • Optional headers that convel addtional information for the servers;
  • Or a body, for some methods like POST, similar to those in responses, which contain the resource sent.

Request header: Headers containing more information about the resource to be fetched or about the client itself.

To HTTP method, here some specific description:

Method Description
GET to request a representation of the specified resource
HEAD same to GET, but without the response body
POST to submit an entity to the specified resource, often causing a change in state or side effects on the server
PUT to replace all current representations of the target resource with the request payload
DELETE to delete the specified resource
CONNECT to establish a tunnel to the server indentified by the target resoure
OPTIONS to describe the communication options for the target resource
TRACE to perform a message loop-back test alone the path to the target resource
PATCH to apply partial modifications to a resource



Responses consist of the following elements:

  • The version of the HTTP protocol they follow;
  • A status code, indicating if the request has been successful, or not, and why;
  • A status message, a non-authoritative short description of the status code;
  • HTTP headers, like those for requests;
  • Optionally, a body containing the fetched resource.

Response header: Headers with addtional information about the response, like its location or about the server itself (name and version etc.).

Here are some response headers:

Response Header Description
Allow Lists the set of HTTP request methods support by a resource.
Server Contains information about the software used by the origin server to handle the request.
Message Body Information
Content-Encoding Used to specify the compression algoritm
Content-Length Indecates the size of the entity-body
Content-Type Indicates the media type of the resource
Location Indicates the URL to redirect a page to.
Last-Modified It is a validator, the last modification date of the resource. Conditional requests using If-Modified-Since and If-Unmodified-Since use this value to change the behavior of the request.
Expires The date/time after which the response is considered state
Set-Cookie Send cookies from the server to the user agent.
WWW-Authontication Defines the authenication method that should be used to gain access to a resource.
Date Contains the date and time at which the message was originated
Refresh Indicates how much time the browser should refresh the document (s)


Here is a syntax example:

Content-Type: text/html; charset=utf-8
Content-Type: multipart/form-data; boundary=something

Here a simple explantion again:

  • media-type - The MIME type (type/subtype; parameter=value) of the resource or the data;
  • charset - The character encoding standard;
  • boundary

[Http Status Code]

Here are some often-used status code.

Status Code Description
Information Response
100 Continue The interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished.
Successful Response
200 OK The request has succeeded.
Redirection Messages
301 Moved Permanently This response code means that the URI of the requested resource has been changed permanently.
302 Found This response code means that the URI of the requested resource has been changed temporarily.
Client Error Responses
404 Not Found The server can not find requested resource.
Server Error Responses
500 Internal Server Error The server has encountered a situation it doesn’t know how to handle.


'use strict'

let str = '{"name": "Jack", "age": 29}';
let str2obj = JSON.parse(str);
let obj2str = JSON.stringify(str2obj);


console.log(typeof str2obj);
console.log(typeof obj2str);

// $ node main
// { name: 'Jack', age: 29 }
// {"name":"Jack","age":29}
// object
// string


1 https://www.soswebdesign.com/gallery/webstandards.cfm

2 https://developer.mozilla.org/en-US/docs/Glossary/SEO

3 https://github.com/mqyqingfeng/Blog/issues/2

4 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

5 https://www.cnblogs.com/lvdabao/p/es6-promise-1.html

6 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions