Chapter2 JavaScript in HTML
2.1 The <script>
Element
- Attribute for script
Attribute | Description |
---|---|
async | Indicates that the script should begin downloading immediately but should not prevent other actions on the page |
charset | |
defer | deferred until after the document’s content has been completely parsed and displayed |
src | |
type | default text/javascript |
- Without defer and async, the <script> elements are interpreted in the order in which they appear in the page
2.2 Inline Code Versus External Files
2.3 Document Mode
2.4 The <noscript>
Element
If browser does not support Javascript, it will show up
1
2
3
4
5<body>
<noscript>
<p>This page requires a JavaScript-enabled browser.</p>
</noscript>
</body>
Chapter3 Language Basics
3.1 Syntax
Strict mode
- Some of the erratic behavior of ECMAScript 3 is addressed and errors are thrown for unsafe activities
- Enable strict mode for an entire script: include
"use strict";
in js top Enable strict mode for a function:
1
2
3
4function doSomething() {
;
// code
}
3.2 Keywords And Reserved Words
3.3 Variables
- ECMAScript variables are loosely typed
Scope
1
2
3
4function test() {
var a = 1; // local variable
b = 2; // global variable
}
3.4 Data Types
- There are five primitive types in ECMAScript:
- Undefined
- Null
- Boolean
- Number
- String
3.4.1 The typeof Operator
Usage
1
2
3var msg = "aaa";
alert(typeof msg);
alert(typeof(msg));
- Return string
Return | Description |
---|---|
undefined | if the value is undefined |
boolean | |
string | |
number | |
object | if the value is an object or null |
function |
3.4.2 The Undefined Type
1 | var a; |
3.4.3 The Null Type
- A null value is an empty object pointer
- so
typeof null === "object" //true
- so
- The value undefined is a derivative of null
- so
null == undefined //true
- so
3.4.4 The Boolean Type
Type | Values converted to true | Values converted to false |
---|---|---|
Boolean | true | false |
String | Any nonempty string | “” |
Number | Any nonzero number | 0 |
Object | Any object | null |
Undefined | NA | undefined |
3.4.5 The Number Type
- base 8:
var octalNum = 070;
- base 16:
var hexNum = 0xA;
- e-notation:
var floatNum = 3.125e7
- Infinity
- max number:
Number.MAX_VALUE
- min number:
Number.MIN_VALUE
- positive infinity:
Infinity
orNumber.POSITIVE_INFINITY
- negative infinity:
-Infinity
orNumber.NEGATIVE_INFINITY
isInfinite(xxx)
- max number:
- NaN(Not a Number)
- any number divided by not number:
10/"abc"
- any NaN operation:
NaN/10
- NaN is not equal to any value, including NaN:
NaN == NaN //false
isNaN()
: determine if the value is “not a number.”
- any number divided by not number:
- Number Conversions
- Immutable
- If the value has a toString() method, it is called (with no arguments) and the result is returned.
- If the value is null, “null” is returned.
- If the value is undefined, “undefined” is returned
3.4.7 The Object Type
var o = new Object()
- Each Object instance has the following properties and method
Property | Description |
---|---|
constructor | function that was used to create the object |
hasOwnProperty(propertyName) | Indicates if the given property exists on the object instance (not on the prototype) |
isPrototypeOf(object) | Determines if the object is a prototype of another object |
propertyIsEnumerable(propertyName) | using the for-in statemen |
toLocaleString() | |
toString() | |
valueOf() |
3.5 Operators
- Identically Equal and Not Identically Equal
55 == "55" //true
55 === "55" //false
3.6 Statement
- Labeled Statement
label: statement
- used with
continue
andbreak
The With Statement
The with statement sets the scope of the code within a particular object
1
2
3
4
5
6
7
8var qs = location.search.substring(1);
var hostName = location.hostname;
var url = location.href;
// the same as
with(location){
var qs = search.substring(1); var hostName = hostname;
var url = href;
}
* DO NOT USE WITH:
> Chapter 24.2: With statement creates its own scope and therefore increases the length of the scope chain for code executed within it
3.7 Functions
Parameters are only for convenience:
1
2
3
4
5function sayHi(a, b) {
alert(typeof b);
alert(typeof a);
}
sayHi(123); // it worksarguments
in functionarguments.length
arguments[0]
but arguments is not an Array instance
- No Overloading
Chapter4 Variables, Scope, and Memory
4.1 Primitive And Reference Values
- Similar as Python:
- primitive type copy value: stored in stack
- reference type copy reference (pointer): stored in heap
instanceof
: if the variable is an instance of the given reference type1
2
3alert(person instanceof Object);
alert(colors instanceof Array);
alert(pattern instanceof RegExp);
4.2 Execution Context And Scope
- Each execution context has an associated variable object upon which all of its defined variables and functions exist
- There are only two primary types of execution contexts
- global
- function (local)
4.2.1 Scope Chain Augmentation
- There are two way to augment the scope chain
- try-catch
- with
4.2.2 No Block-Level Scopes
1 | for(var i = 0; i < 10; i++){ |
4.3 Garbage Collection
- Two ways:
- mark-and-sweep
- reference counting
4.3.1 mark-and-sweep:
- Delete variable that cannot be fetched
4.3.2 reference counting
- Delete variable that reference count == 0
Issue: circular reference
1
2
3
4var element = document.getElementById("some_element");
var myObject = new Object();
myObject.element = element;
element.someObject = myObject;
4.3.3 Performance
4.3.4 Managing Memory
Dereference
The point of dereferencing is to make sure the value is out of context and will be reclaimed the next time garbage collection occurs. e.g.
1 | var p = createPerson("name"); |
Chapter5 Reference Types
5.1 The Object Type
Two ways to explicitly create an instance of Object:
1
2
3
4
5var person = new Object(); // constructor
person.age = 10;
person.name = "aaa";
var person = {age:10, name:"aaa"}; // object literal notation
- Two ways to access attribute
person.name
: preferredperson["name"]
: used in case likeperson["last name"]
5.2 The Array Type
Two ways to explicitly create an instance of Array:
1
2
3
4
5
6var colors = new Array(); // constructor
var colors = new Array(20); // length
var colors = new Array(1, "aaa", obj); // can store any types
var colors = []; // array literal notation
var colors = [1, 3];access, update
1
2
3
4
5
6var colors = [1, 3];
colors[4] = "aaa"; // [1, 3, , , "aaa"]
colors[3]; // undefined
colors.length = 2; // [1, 3]
colors.length = 6; // [1, 3, , , ,]
colors[3]; // undefined
5.2.1 Detecting Arrays
- Reason:
- The one problem with
instanceof
assumes a single global execution context - If an array was passed from one frame into another frame, that array has a different constructor function.
- So
instanceof
fail.
- The one problem with
- Solution
if (Array.isArray(colors))
5.2.2 Conversion Methods
- toLocalString()
- toString()
- valueOf()
5.2.3-5.2.7
var nums = [0, 1, 2]
Type | Function | Description |
---|---|---|
Stack | push(1, 2) | [0, 1, 2, 1, 2] |
Stack | pop() | [0, 1] |
Queue | shift() | [1, 2] |
Queue | unshift(1, 2) | [1, 2, 0, 1, 2] |
Reordering | reverse() | [2, 1, 0] |
Reordering | sort(func) | a function for comparation |
Manipulation | concat(3, [4, 5]) | [0, 1, 2, 3, 4, 5] |
Manipulation | slice() | slice(1): from index 1 to last slice(1, 2): from index 1 to index 2 (excluded) |
Matipulation | splice() | deletion: splice(0, 3) // delte from index 0 for 3 element insertion: splice(2, 0, “123”) // insert “123” into index 2, delete 0 element replacement: splice(2, 1, “123”) // insert “123” into index 2, delete 1 element |
Location | indexOf() | search from first element |
Location | lastIndexOf() | search from last element |
Iterative | every() | colors.every(function(item, index, array) {return item > 2;}); |
Iterative | some() | similar as every() |
Iterative | filter() | colors.filter(function(item, index, array) {return item > 2;}); |
Iterative | forEach() | colors.map(function(item, index, array) {...}); |
Iterative | map() | colors.map(function(item, index, array) {return item * 2;}); |
Reduction | reduce() | like foldl in Go. From first item |
Reduction | reduceRight() | like foldr in Go. From last item |
5.3 THE DATE TYPE
Hard to say
5.4 THE REGEXP TYPE
flags:
Type | Description |
---|---|
g | global |
i | case insensitive |
m | multiline |
1 | var re = /[bc]at/i; // var expression = /pattern/ flags |
5.4.1 RegExp Instance Properties
Type | Description |
---|---|
global | if g |
ignoreCase | if i |
multiline | if m |
lastIndex | start position of next search |
source | pattern information |
5.4.2 RegExp Instance Methods
exec()
1
2
3
4
5
6var text = "...";
var pattern = /xxx/;
var matches = pattern.exec(text);
alert(matches.index);
alert(matches.input);
alert(matches[0]);
- test():
pattern.test(text) // return boolean
5.4.3 RegExp Constructor Properties
VERBOSE NAME | SHORT NAME |
---|---|
input | $_ |
lastMatch | $& |
lastParen | $+ |
leftContext | $` |
multiline | $* |
rightContext | $’ |
usage:
1 | if (pattern.test(text)) { |
5.4.4 Pattern Limitations
5.5 The Function Type
- Each function is an instance of the Function type
- Functions are actually Object
func instanceof Object // true
- Function names are actually reference
Three ways to creat a function:
1 | // function declaration |
5.5.1 No Overloading
Because function name is reference
5.5.2 Function Declarations versus Function Expressions
- Function declarations are read and available in an execution context before any code is executed
Function expressions aren’t complete until the execution reaches that line of code.
1
2
3
4
5
6
7
8
9
10
11// works
alert(sum(10, 10));
function sum(num1, num2) {
return num1 + num2;
}
// error
alert(sum(10, 10));
var sum = function(num1, num2) {
return num1 + num2;
};
5.5.3 Functions as Values
- function can be parsed as argument and return
5.5.4 Function Internals
- arguments
arguments.callee
: the function, can be used for recursion
this
It is a reference to the context object that the function is operating on.
1
2
3
4
5
6
7window.color = "red";
var o = { color: "blue" };
function sayColor(){ alert(this.color);}
sayColor(); //"red"
o.sayColor = sayColor;
o.sayColor(); //"blue"
The interpreter updates the ThisBinding whenever establishing an execution context in one of only three different cases:
- Initial global execution context
- Entering eval code
- Entering function code
- In most other cases, ThisBinding is set to the global object
- If a function is called on an object, such as in
obj.myMethod()
or the equivalentobj["myMethod"]()
, then ThisBinding is set to the object.
- Opposite:
var a = obj.myMethod; a();
this bind to window- These special functions take a so-called thisArg which becomes the ThisBinding when calling the function
- Function.prototype.apply( thisArg, argArray )
- Function.prototype.call( thisArg [ , arg1 [ , arg2, … ] ] )
- Function.prototype.bind( thisArg [ , arg1 [ , arg2, … ] ] )
- Array.prototype.every( callbackfn [ , thisArg ] )
- Array.prototype.some( callbackfn [ , thisArg ] )
- Array.prototype.forEach( callbackfn [ , thisArg ] )
- Array.prototype.map( callbackfn [ , thisArg ] )
- Array.prototype.filter( callbackfn [ , thisArg ] )
- new operation
1 | function MyType() { |
- caller
- A reference to the function that called this function or null if the function was called from the global scope.
5.5.5 Function Properties and Methods
Two properties
- length: number of arguments expected
- prototype
- actual location of all instance methods for reference types
- methods such as toString(), valueOf() exist on prototype
Two methods
func.apply(context, arguments):
1
2
3
4
5
6
7
8function sum(num1, num2) {return num1 + num2;}
function callSum(num1, num2) {
// so this refer to global. The same as call sum(arguments) in global
return sum.apply(this, arguments);
}
alert(callSum(10, 10)); // this function is invoked in global
- func.call(context, arg1, arg2, …)
- Similar as apply()
- Only difference is argument should be parsed one by one
- Usage:
sum.call(this, num1, num2);
Their ability to augment context inside of the function
1
2
3sayColor.call(this);
sayColor.call(window);
sayColor.call(obj);
bind(context)
- It returns a function instance
bind
this
to function1
2
3
4
5
6var o = {"color": "blue"};
function sayColor() {
alert(this.color);
}
var objSayColor = sayColor.bind(o);
objSayColor(); // blue
5.6 Primitive Wrapper Types
Three special reference types:
- The Boolean type:
var b = new Boolean(false)
- The Number type:
var n = new Number(10)
- The String type:
var s = new String("abbb")
Reason:
"aaaaa".substring(2)
is valid- “aaaaa” is primitive type, shoule not have method. These steps happened:
- Create an instance of the String type.
- Call the specified method on the instance.
- Destroy the instance.
5.6.1 The Boolean Type
DO NOT USE IT.
Unexpted behaviour when doing logic operation
5.6.2 The Number Type
Method | Description |
---|---|
valueOf() | |
toLocaleString() | |
toString() | |
toFixed() | 10.005.toFixed(2) // 10.01 |
toExponential() | 10.toExponential(1) // 1.0e+1 |
toPrecision() | fixed or exponential |
5.6.3 The String Type
Type | Method |
---|---|
Character Methods | charAt() charCodeAt() “xxx”[0] |
String-Manipulation Methods | concat() slice() substring() substr() |
String Location Methods | indexOf() lastIndexOf() |
The trim() Method | trim() |
String Case Methods | toLowerCase() toLocalLowerCase() toUpperCase() toLocalUpperCase() |
String Pattern-Matching Methods | 5.4 RE match() replace() htmlEscape() split() |
The localeCompare() Method | |
The fromCharCode() Method | |
HTML Methods |
5.7 Singleton Built-In Objects
5.7.1 The Global Object
- All variables and functions defined globally become properties of the Global object
- All variables and functions are Global methods. e.g. parseInt(), isNaN()
URI-Encoding Methods
- encodeURI()/decodeURI()
- encodeURIComponent()/decodeURIComponent()
The eval() Method
- It interprets the argument into actual ECMAScript statements and then inserts it into place
Has the same scope chain
1
2eval("function sayHi() {alert('hi');}");
sayHi()
Global Object Properties
Special Values:
- undefined
- NaN
- Infinity
Constructors:
- Object, Array, Function, Boolean, String, Number, Date, RegExp, Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError
The Window Object
- Though ECMAScript doesn’t indicate a way to access the Global object
- Web browsers implement it such that the
window
is the Global object’s delegate The
window
object doesmuch more
in JavaScript than just implement the ECMAScript Global object1
2
3
4
5var color = "red";
function sayColor(){
alert(window.color);
}
window.sayColor(); //"red"
5.7.2 The Math Object
Properties
- Math.E, Math.LN10, Math.LN2, Math.LOG2E, Math.LOG10E, Math.PI, Math.SQRT1_2, Math.SQRT2
Methods
- min(), max()
- ceil(), floor(), round()
- random()
- abs(), exp(), log(), pow(), sqrt(), acos(), asin(), atan(), atan2(), cos(), sin(), tan()
Chapter6 Object-Oriented Programming
6.1 Understanding Objects
6.1.1 Types of Properties
- Data Property:
- Each data property has 4 attributes
Name | Description |
---|---|
[[Configurable]] | if can be delete person.name , false: cannot change any attributes |
[[Enumerable]] | if the property can be for-in loop |
[[Writable]] | if value can be changed |
[[Value]] | the value |
- Accessor Properties
- It defines
getter
andsetter
- It defines
Name | Description |
---|---|
[[Configurable]] | same |
[[Enumerable]] | same |
[[Get]] | getter |
[[Set]] | setter |
6.1.2 Defining Multiple Properties
1 | var person = {}; |
6.1.3 Reading Property Attributes
1 | var descriptor = Object.getOwnPropertyDescriptor(person, "name"); |
6.2 Object Creation
6.2.1 The Factory Pattern
1 | function createPerson(name, age){ |
- Disadvantage:
- Cannot know instance type
- Different people has different
sayName
function
6.2.2 The Constructor Pattern
1 | function Person(name, age){ |
Advantages:
1
2
3var person1 = new Person("N", 11);
person1.constructor == Person // true
person1 instanceOf Person // true
- Disadvantages:
- Different people has different
sayName
function - Make
sayName
global thenthis.sayName = sayName
is not a solution since the method should be private - User is able to call
Person(xx, xx)
withoutnew
, then it sets global attribute
- Different people has different
6.2.3 The Prototype Pattern
By scope chain:
person1.name
first searchperson1
attribute then its Prototypeperson1.sayName()
first searchperson1
then its Prototype
Advantages:
person1.name == "NG"
covers the Prototype onedelte person1.name
can recover it- all person instances share the same sayName function
Disadvantages:
- different people should have different attributes
- If the name is an Object, it is mutable and change the name of all persons
Syntax
1
2
3
4
5
6
7
8
9function Person(){}
Person.prototype = {
constructor: Person,
name : "Nicholas",
age : 29,
sayName : function () {
alert(this.name);
}
};Some methods
1
2
3
4
5
6
7
8
9Object.getPrototypeOf(person1) == Person.prototype // true
Object.getPrototypeOf(person1).name // "Nicholas"
person1.hasOwnProperty("name") // false: if returned attribute got from instance
person1.hasOwnPrototypeProperty("name") // true: if returned attribute got from prototype
"name" in person1 // true: if has "name" no matter in instance or prototype
Object.keys() // all instance enumerated attributes
Object.getOwnPropertyNames() // all instance attributes even not enumerated
6.2.4 Combination Constructor/Prototype Pattern
1 | function Person(name, age){ |
- Disadvantage:
- Confused because having two code blocks for a class
6.2.5 Dynamic Prototype Pattern
1 | function Person(name, age){ |
6.2.6 Parasitic Constructor Pattern
1 | function Person(name, age, job){ |
Does not make sense!!! Cannot see any advantages over 6.2.5
6.2.7 Durable Constructor Pattern
1 | function Person(name, age, job){ |
Does not make sense!!! Cannot see any advantages over 6.2.5
6.3 Inheritance
6.3.1 Prototype Chaining (hardly use)
The basic idea is to use the concept of prototypes to inherit properties and methods between two reference types
1 | function SuperType(){ |
1 | alert(instance instanceof Object); // true |
Issues:
When prototypes contain reference values
1
2
3
4
5
6
7function SuperType() {
this.colors = ["r", "g", "b"]
}
...
instance1.colors.push("w");
alert(instance2.colors); // r, g, b, wcannot pass arguments into the supertype
6.3.2 Constructor Stealing
1 | function SuperType(name){ |
Because of 5.5.4, it cannot be SuperType.call(“Nicholas”)
Advantages: It solves 6.3.1 issues.
Disadvantages:
- no function reuse. (instances have their own function)
- methods defined on the supertype’s prototype are not accessible on the subtype
6.3.3 Combination Inheritance
(combined with 6.3.1 and 6.3.2)
1 | function SuperType(name){ |
Advantage:
- The most frequently used inheritance pattern in JavaScript.
instanceof
,isPrototypeOf()
also work
Disadvantage:
- call two times of SuperType()
6.3.4 Prototypal Inheritance
Basic idea:
1 | function object(o){ |
ECMA5: formalized the concept of prototypal inheritance by Object.create(parentInstance)
1 | var person = { |
- Advantages: easy
- Disadvantages:
- need a parent instance created
- share mutable type attributes. i.e. friends list
6.3.5 Parasitic(寄生式) Inheritance
Similar as 6.3.4
1 | function createAnother(original){ |
Disadvantage:
* the same as 6.3.4
* function reuse inefficiencies
6.3.6 Parasitic Combination(寄生组合式)Inheritance
看不懂!!!!
1 | function inheritPrototype(subType, superType){ |
Parasitic combination inheritance is considered the most efficient way to implement type-based inheritance.
Chapter7 Function Expressions
7.1 Recursion
- use arguments.callee
a special implementation
1
2
3
4
5
6
7
8var factorial = (function f(num) {
if (num <= 1) {
return 1;
}
else {
return num * f(num-1);
}
}
7.2 Closure
Closures are functions that have access to variables from another function’s scope. This is often accomplished by creating a function inside a function
7.2.1 Closures and Variables
Should understand the difference between
1 | function createFunctions(){ |
1 | function createFunctions(){ |
7.2.2 The this Object
Should understand the difference between
1 | var name = "The Window"; |
1 | var name = "The Window"; |
7.2.3 Memory Leaks
Closure will store variables in memory and cannot be destroied.
1 | function assignHandler(){ |
Solution
1
2
3
4
5
6
7
8function assignHandler(){
var element = document.getElementById("someElement");
var id = element.id;
element.onclick = function(){
alert(id);
};
element = null;
}
7.3 MIMICKING BLOCK SCOPE
JavaScript has no concept of block-level scoping
1 | for (var i=0; i < 2; i++){ |
Solution
1
2
3
4var someFunction = function(){
//block code here
};
someFunction();1
2
3
4
5
6
7function(){
//block code here
}(); //error! Because of Javascript declaration hoisting
(function(){
//block code here
})(); //fine
7.4 PRIVATE VARIABLES
Privileged method: two ways
1 | function MyObject(){ |
1 | function Pewrson(name) { |
Disadvantage: each time new Person
, new functions are created
7.4.1 Static Private Variables
1 | (function(){ |
Disadvantage: All instance name will be shared and set
7.4.2 The Module Pattern
Create private variable and privileged method for singleton
1 | var singleton = function(){ |
7.4.3 The Module-Augmentation Pattern
1 | var singleton = function(){ |
Chapter8 BOM(Browser Object Model)
Provides objects that expose browser functionality independent of any web page content
8.1 THE WINDOW OBJECT
Dual purpose:
- JavaScript interface to the browser window
- ECMAScript Global object
8.1.1 The Global Scope
1 | var age = 19; |
Cannot
delete window.age
: properties of window that were added via var statements have their [[Configurable]] attribute set to falseAttempting to access an undeclared variable throws an error, but it is possible to check for the existence of a potentially undeclared variable by looking on the window object.
1
2var newValue = oldValue; // err
var newValue = window.oldValue; // undefined
8.1.2-8.1.7 Window Relationships and Frames
Category | Name | Description |
---|---|---|
Frames | frames[0] |
access to window object for different frame |
top |
the very top (outermost) frame, which is the browser window itself | |
parent |
The parent object always points to the current frame’s immediate parent frame | |
Window Position | screenLeft |
|
screenTop |
||
moveTo() |
||
moveBy() |
||
Window Size | innerWidth |
|
innerHeight |
||
outerWidth |
||
outerHeight |
||
resizeTo() |
||
resizeBy() |
||
Navigating and Opening Windows | open() |
|
close() |
||
Intervals and Timeouts | setTimeout() |
|
clearTimeout() |
||
setInterval() |
||
clearInterval() |
||
System Dialogs | alert() |
|
confirm() |
||
promp() |
||
print() |
print dialog | |
find() |
search dialog |
8.2 THE LOCATION OBJECT
- It provides information about the document
window.location === document.location
Location Attributes
https://movie.douban.com/subject/1291561/?from=showing
as example
Category | Name | Description |
---|---|---|
hash | “” | The URL hash or an empty string if the URL doesn’t have a hash. |
host | “movie.douban.com” | |
href | “https://movie.douban.com/subject/1291561/?from=showing" | |
pathname | “/subject/1291561/“ | |
port | “” | |
protocol | “https:” | The protocol used by the page. Typically “http:” or “https:”. |
search | “?from=showing” | search string which start with ? |
Manipulating the Location
Name | Description |
---|---|
location.assign("http://www.wrox.com"); |
|
window.location = "http://www.wrox.com" |
|
location.href = "http://www.wrox.com" |
location.search = "?q=javascript"; location.hostname = "www.yahoo.com"; … |
location.replace("http://www.wrox.com") |
user cannot click back button to the previous page |
location.reload() |
8.3 THE NAVIGATOR OBJECT
For providing browser information
8.4 THE SCREEN OBJECT
An indication of client capabilities
8.5 THE HISTORY OBJECT
represents the user’s navigation history
Name | Description |
---|---|
history.go(-1) |
go back one page |
history.go(1) |
go forward one page |
history.go("wrox.com") |
go to nearest wrox.com page |
history.forward() |
same as history.go(1) |
history.back() |
same as history.go(-1) |
Chpater9 Client Detection
9.1 Capability detection
Tests for specific browser capabilities before using them
9.3 Quirks detection
Quirks are essentially bugs in browser implementations
9.3 User-agent detection
Detecting information about the browser, often including the browser, platform, operating system, and browser version.
Chapter10 DOM(Document Object Model)
Represents a document as a hierarchical tree of nodes, allowing developers to add, remove, and modify individual parts of the page.
10.1 HIERARCHY OF NODES
10.1.1 The Node Type
- Node.ELEMENT_NODE (1)
- Node.ATTRIBUTE_NODE (2)
- Node.TEXT_NODE (3)
- Node.CDATA_SECTION_NODE (4)
- Node.ENTITY_REFERENCE_NODE (5)
- Node.ENTITY_NODE (6)
- Node.PROCESSING_INSTRUCTION_NODE (7)
- Node.COMMENT_NODE (8)
- Node.DOCUMENT_NODE (9)
- Node.DOCUMENT_TYPE_NODE (10)
- Node.DOCUMENT_FRAGMENT_NODE (11)
- Node.NOTATION_NODE (12)
var someNode = document.getElementById('xx')
nodeName and nodeValue
Name | usage | Description |
---|---|---|
nodeType | someNode.nodeType === Node.ELEMENT_NODE |
|
nodeName | someNode.nodeName === 'DIV' |
tag |
childNodes | someNode.childNodes[0] someNode.childNodes.item(1) |
Each node has a childNodes property containing a NodeList obj Changes will be reflected in NodeList objects automatically (dynamic) |
parentNode | someNode.parentNode |
|
previousSibling | someNode.previousSibling |
|
nextSibling | someNode.nextSibling |
|
firstChild | someNode.firstChild |
|
lastChild | someNode.lastChild |
|
appendChild | someNode.appendChild(newNode) |
|
insertBefore | someNode.insertBefore(newNode, aChildNode) |
if null, become last node |
replaceChild | someNode.replaceChild(newNode, aChildNode) |
|
cloneNode | someNode.cloneNode(true) |
boolean: copy all children or not |
normalize | … |
10.1.2 The Document Type
- Represents document nodes
- The document object in browser is an instance of HTMLDocument
- The document object is a property of window and is accessible globally
Category | Usage | Description |
---|---|---|
Document Childre | document.documentElement | <html> |
document.body | <body> |
|
document.doctype | <!DOCTYPE> |
|
Document Information | ||
document.title | ||
document.URL | ||
document.domain | ||
document.referrer | gives the URL of the page that linked to this page | |
Locating Elements | getElementById() | return the first occurance |
document.getElementByTagName() | return a HTMLCollection obj, dynamicimages.namedItem("myImage") or images["myImage"] parameter can be ‘*” |
|
document.getElementByName() | similar as getElementByTagName | |
Special Collections | document.anchors | Contains all \ elements with a name attribute |
document.forms | <form> |
|
document.images | <img> |
|
document.links | Contains all \ elements with an href attribute | |
DOM Conformance Detection | document.implementaion.hasFeature(‘XML’’, ‘1.0’) | |
Document Writing | write() | |
document.writeln() | ||
document.open() | ||
document.close() |
10.1.3 The Element Type
Name | Description |
---|---|
element.getAttribute() | custom attributes should be prepended with data- in order to validate |
element.setAttribute() | |
element.removeAttribute() | |
element.attributes | .getNamedItem(name) .removeNamedItem(name) .setNamedItem(node) .item(pos) |
document.createElement() | createElement("div");div.id="newDiv" or createElement("\<div id=\\"newDiv\\"\>\<div>") ; |
10.1.4 The Text Type
Category | Name | Description |
---|---|---|
text manipulation | appendData(text) | |
deleteData(offset, count) | ||
insertData(offset, count) | ||
replaceData(offset, count, text) | ||
splitText(offset) | ||
substringData(offset, count) | ||
create text node | createTextNode(“text”) | |
normalize text nodes | element.normalize() | it is possible to have multiple text nodes as children |
split text nodes | element.firstChild.splitText(5) |
10.1.5 The Comment Type
- Inherits from the same base as the Text type, so it has all of the same string- manipulation methods except splitText()
- document.createComment()
10.1.6 The CDATASection Type
- CDATA sections are specific to XML-based documents
- document.createCDataSection()
10.1.7 The DocumentType Type
document.doctype.name === 'HTML'
- e.g.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
: HTML
10.1.8 The DocumentFragment Type
Adding each item directly to the element causes the browser to re-render the page with the new information. It solves this issue.
1 | var fragment = document.createDocumentFragment(); |
10.1.9 The Attr Type
Not recommended.
Another way of get/set/removeAttribute()
.
10.2 WORKING WITH THE DOM
10.2.1 Dynamic Scripts
1 | function loadScript(url){ |
10.2.2 Dynamic Styles
1 | function loadStyles(url){ |
10.2.3 Manipulating Tables
Skip, I guess no one do this by hand
10.2.4 Using NodeLists
NodeList, NamedNodeMap and HTMLCollection are similar: all dynamic
Since a query is run against the document each time, try to cache frequently used values retrieved from a NodeList. e.g.
1
2var divs = document.getElementsByTagName('div');
var len = divs.length;
Chapter11 DOM Extensions
11.1 SELECTORS API
Category | Example | Description |
---|---|---|
querySelector() | document.querySelector(“body”) | “body”, “#myId”, “.myClass” return first element |
querySelectorAll() | document.querySelectorAll(“. myClass”); | return NodeList obj |
matchesSelector() | document.body.matchesSelector("body.page1") === true |
11.2 ELEMENT TRAVERSAL
Category | Example |
---|---|
childElementCount | number of child elements |
firstElementChild | |
lastElementChild | |
previousElementSibling | |
nextElementSibling |
1 | var i, len, |
11.3 HTML 5
Category | Name | Description |
---|---|---|
Class-Related Additions | getElementsByClassName() | return NodeList |
classList.add(value) .contains(value) .remove(value) .toggle(value) |
||
Focus Management | document.activeElement | contains a pointer to the DOM element that currently has focus |
element.focus() | ||
document.hasfocus() | determine if the user is interacting with the page | |
Changes to HTMLDocument | document.readyState | loading: The document is loading complete: The document is completely loaded |
document.compatMode | CSS1Compat: standard BackCompat: quirks mode |
|
document.head | ||
Character Set Properties | document.charset | “UTF-16” |
Custom Data Attributes | element.dataset | customed data attributes should begin with “data-“, then can be fetched by element.dataset.myname; <div id="myDiv" data-myname="Nicholas"></div> |
Markup Insertion | innerHTML | return the HTML representing all of the child nodes |
outerHTML | all innerHTML and it self | |
insertAdjacentHTML(position, text) | position = [“beforebegin”, “afterbegin”, “beforeend”, “afterend”] | |
scrollIntoView | scrollIntoView(boolean) | make sure an element is visible |
11.4 PROPRIETARY EXTENSIONS
Name | Description |
---|---|
document.documentMode |
determines which features it has access |
document.documentElement.contains(document.body) |
|
document.documentElement.compareDocumentPosision(another) |
1, 2, 4, 8 16 |
innerText |
read/write all children text content |
outerText |
read all children text content, write all children including itself |
scrollIntoViewIfNeeded() |
Scrolls only if it’s not already visible |
scrollByLines(lineCount) |
|
scrollByPages(pageCount) |
Chapter12 DOM Levels 2 and 3
12.1 DOM CHANGES
12.1.1 XML Namespaces
Skip. I think it is gradually replaced by json
12.1.2 Other Changes
Changes to DocumentType
1 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd" |
- publicId: “-//W3C//DTD HTML 4.01//EN”,
- systemId: “http://www.w3.org/TR/html4/strict.dtd",
- internalSubset: “<!ELEMENT name (#PCDATA)”
Changes to Document
Name | Description |
---|---|
importNode(oldNode, boolean) | Similar as cloneNode() boolean: if copy children |
document.implementaion | createDocumentType() createDocument() createHTMLDocument() |
Changes to Node
Name | Description |
---|---|
element.isSameNode() | same reference |
element.isEqualNode() | same attributes |
element.setUserData(key, value, operationCallback) | whenever the node with the data is cloned, removed, renamed, or imported into another document |
element.getUserData(key) |
Changes to Frames
This property contains a pointer to the document object representing the contents of the frame.
document.getElementById("frameId").contentDocument
12.2 STYLES
12.2.1 Accessing Element Styles
Any HTML element that supports the style attribute also has a style property exposed in JavaScript
CSS PROPERTY | JAVASCRIPT PROPERTY |
---|---|
background-image | element.style.backgroundImage |
color | element.style.color |
display | element.style.display |
font-family | element.style.fontFamily |
Some attributes/methods
- cssText
myDiv.style.cssText = "width: 25px;"
- length
- parentRule
- getPropertyCSSValue(propertyName)
- getPropertyPriority(propertyName)
- getPropertyValue(propertyName)
- item(index)
- removeProperty(propertyName)
- setProperty(propertyName, value, priority)
- getComputedStyle()
- get the actual style after overriding
12.2.2 Working with Style Sheets
CSS Style Sheets
- CSSStyleSheet extends StyleSheet
- Access by:
document.styleSheets
- Attributes:
- disabled
- href
- media
- ownerNode
- parentStyleSheet
- title
- type
- cssRule
- ownerRule
- deleteRule(index)
- insertRule(rule, index)
CSS Rules
- CSSStyleRule extends CSSRule
- Access by:
document.styleSheets[0].cssRule
Attributes
- cssText
- parentRule
- parentStyleSheet
- selectorText
- style
- type
Operations:
- sheet.insertRule(ruleText, insertIndex)
- sheet.deleteRule(index)
12.2.3 Element Dimensions
Category | Function | Description |
---|---|---|
offset dimension | offsetHeight | |
offsetWidth | ||
offsetLeft | ||
offsetTop | ||
Client Dimensions | clientWidth | |
clientHeight | ||
Scroll dimension | scrollHeight | |
scrollWidth | ||
scrollLeft | ||
scrollTop | ||
Element location | getBoundingClientRect().left/right/top/bottom | location of the element on the page relative to the viewport |
12.3 TRAVERSALS
Depth-first: NodeIterator, TreeWalker
12.3.1 NodeIterator
document.createNodeIterator(root, whatToShow, filter, entityReferenceExpansion)
- root: search root
- whatToShow: A numerical code indicating which nodes should be visited
filter: instance of NodeFilter.
var iterator = NodeFilter.SHOW_ALL
var iterator = NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT
an obj contained function
acceptNode
1
2
3
4
5var filter = {
acceptNode: function(node){
return node.tagName.toLowerCase() == "p" ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
}
};a function:
1
2
3
4
5var filter = function(node){
return node.tagName.toLowerCase() == "p" ?
NodeFilter.FILTER_ACCEPT :
NodeFilter.FILTER_SKIP;
};
entityReferenceExpansion: not useful
The two primary methods of NodeIterator
nextNode()
previousNode()
12.3.2 TreeWalker
An advanced version of NodeIteratordocument.createTreeWalker(root, whatToShow, filter, entityReferenceExpansion)
methods:
- nextNode()
- previousNode()
- parentNode()
- firstChild()
- lastChild()
- nextSibling()
- previousSibling()
12.4 RANGES
12.4.1 Ranges in the DOM
Usage:
document.createRange()
Attributes:
- startContainer
- startOffset
- endContainer
- endOffset
- commonAncestorContainer
Simple Selection
- selectNode(): contain node itself
selectNodeContents(): only contain children
Usage:
1
2
3
4
5var range1 = document.createRange(),
range2 = document.createRange(),
p1 = document.getElementById("p1");
range1.selectNode(p1);
range2.selectNodeContents(p1);
setStartBefore(refNode)
- setStartAfter(refNode)
- setEndBefore(refNode)
- setEndAfter(refNode)
Complex Selection
- range.setStart()
- range.setEnd()
Interacting with DOM Range Content
- range.deleteContents()
- range.extractContents()
- range.cloneContents()
- range.insertNode()
- range.surroundContents()
- range.collapse(): not useful
- range1.compareBoundaryPoints(range2)
- check if shared boundary
- It returns
- Range.START_TO_START: 0
- Range.START_TO_END: 1
- Range.END_TO_END: 2
- Range.END_TO_START: 3
- range.cloneRange()
range.detach(); range = null;
: detach from document then dereferenced
12.4.2 Ranges in Internet Explorer 8 and Earlier
Skip
Chapter13 Events
13.1 Events Flow
Example:
1 | <!DOCTYPE html> |
DOM Level 2 Events has three phases
- the event capturing phase
- at the target
- the event bubbling phase
13.2 EVENT HANDLERS
- event name: e.g. click, load
- event handler: e.g. onclick, onload
13.2.1 HTML Event Handlers
<input type="button" value="Click Me" onclick="alert(‘Clicked’)" />
- It tightly couples the HTML to the JavaScript
13.2.2 DOM Level 0 Event Handlers
One method:
Assign a function to an event handler property, which run winthin the scope of element
1
2
3
4
5
6var btn = document.getElementById("myBtn");
btn.onclick = function(){
alert("Clicked");
};
btn.onclick = null; //remove event handler
13.2.3 DOM Level 2 Event Handlers
- Two methods:
addEventListener(eventName, handler, captureOrBubble)
removeEventListener(eventName, handler, captureOrBubble)
- multiple event handlers can be added
- e.g. btn can have two click event
- event fire in the order of adding order
- event added by
addEventListener
can only be removed byremoveEventListener
with same arguments. (anonymous function… haha)
13.2.4 Internet Explorer Event Handlers
Skip
13.2.5 Cross-Browser Event Handlers
Skip
13.3 THE EVENT OBJECT
When an event related to the DOM is fired, all of the relevant information is gathered and stored on an object called event
1 | btn.onclick = function(event){ |
13.3.1 The DOM Event Object
attribute | type | description |
---|---|---|
bubbles | Boolean | if the event bubbles |
cancelable | Boolean | if the default behavior of the event can be canceled. |
currentTarget | Element | The element whose event is handlering |
defaultPrevented | Boolean | indicates that preventDefault() has been called |
detail | Integer | |
eventPhase | Integer | 1: capturing phase, 2: at target, 3: bubbling |
preventDefault() | Function | Cancels the default behavior for the event |
stopImmediatePropagation() | Function | Cancels any further event capturing or event bubbling and prevents any other event handlers from being called |
stopPropagation() | Function | Cancels any further event capturing or event bubbling |
target | Element | The target of the event. |
trusted | Boolean | |
type | String | The type of event that was fired |
view | AbstractView |
currentTarget
vstarget
vsthis
currentTarget === this
- currentTarget indicates where the handler is
target indicates where the action happens
1
2
3
4
5document.body.onclick = function(event){
alert(event.currentTarget === document.body); //true
alert(this === document.body); //true
alert(event.target === document.getElementById("myBtn")); //true
};
- Any event that can be canceled using preventDefault() will have its cancelable property set to true
13.3.2 The Internet Explorer Event Object
Skip
13.3.3 The Cross-Browser Event Object
Skip
13.4 EVENT TYPES
DOM Level 3 Events specifies the following event groups:
- User interface (UI) events
- DOMActive: deprecated
- load: after completely loaded
- window, script, img, body
- unload
- abort: Fires on an \<object> element if it is not fully loaded before the user stops the download process
- error
- select
- resize
- scroll
- Focus events
- blur: Fires when an element has lost focus.
- DOMFocusIn: deprecated
- DOMFocusOut: deprecated
- focus — Fires when an element has received focus
- focusin — Fires when an element has received focus
- focusout — Fires when an element has lost focus.
- When focus is moved from one element to another on the page, the following order of events is followed:
focusout
fires on the element losing focus.focusin
fires on the element receiving focus.blur
fires on the element losing focus.DOMFocusOut
fires on the element losing focus.focus
fires on the element receiving focus.DOMFocusIn
fires on the element receiving focus.
- Mouse events
- click
- dblclick
- mousedown
- mouseenter
- mouseleave
- mousemove
- mouseout
- mouseover
- mouseup
- Wheel events
- mousewheel
- Text events
- text input
- Keyboard events
- keydown
- keypress
- keyup
- Composition events: When inputting characters: like Chinese, Japanese
- Mutation events: when a change occurs to the underlying DOM structure.
- DOMSubtreeModified
- DOMNodeInserted
- DOMNodeRemoved
- DOMNodeInsertedIntoDocument
- DOMNodeRemovedFromDocument
- DOMAttrModified
- DOMCharacterDataModified
- Mutation name events: when element or attribute names are changed
HTML5 Events
- contextmenu: the menu when right mouse click
- beforeunload: prevent the page from being unloaded.
- DOMContentLoaded: fires as soon as the DOM tree is completely formed and without regard to images, JavaScript files, CSS files, or other such resources.
- readystatechange: IE
- pageshow/pagehide:
- back-forward cache speed up page load, while won’t fire load event
- pageshow fires after the load event or page restored
- hashchange: when the URL hash (everything following a pound sign (#) in a URL) changed
Device Events: Skip
Touch and Gesture Events: Skip
13.5 MEMORY AND PERFORMANCE
13.5.1 Event Delegation
Basic idea: gather all same event handler in document
1 | EventUtil.addHandler(list, "click", function(event){ |
- The document object is immediately available and can have event handlers assigned at any point during the page’s life cycle
- Less time is spent setting up event handlers on the page. Assigning one event handler takes fewer DOM references and less time.
- Lower memory usage is required for the entire page, improving overall performance.
13.5.2 Removing Event Handlers
- Dangling event handlers: the event handler remains attached even the element is removed
- Solution: remove event handler
btn.onclick = null;
13.6 SIMULATING EVENTS
13.6.1 DOM Event Simulation
Create event by JavaScript
- UIEvents
- MouseEvents
- MutationEvents
- HTMLEvents
13.6.2 Internet Explorer Event Simulation
Skip
Chapter14 Scripting Forms
14.1 Form Basics
by the
attribute | description |
---|---|
acceptCharset | The character sets that the server can process |
action | URL |
elements | An HTMLCollection of all controls in the form. |
enctype | The encoding type of the request |
length | number of controls in the form |
method | type of HTTP request. e.g. “get” “post” |
name | form name |
reset() | reset all fields to default |
submit() | submit form |
target | The name of the window to use for sending the request and receiving the response |
document.forms[0] or document.forms[1]
14.1.1 Submitting Forms
any \<input> \<button> with type="submit"
can submit form
form.addEventListener(‘submit’, handler);
event.preventDefault(event)
form.submit()
14.1.2 Submitting Forms
form.addEventListener(‘reset’, handler);
event.preventDefault(event)
form.reset()
14.1.3 Form Fields
form.elements[0]
form.elements[‘text1’]
form.elements.length
Common Form-Field Properties
disabled |
form | pointer to this form
name | name
readOnly
tabIndex | tab order
type | checkbox, radio …
value | if file: readonly and contain file path
Common Form-Field Methods
focus() | sets the browser’s focus to the form fi eld
autofocus | <input type="text" autofocus>
blur() | remove focus from element
Common Form-Field Events
blur | lose focus
change | lose focus and value changed for \<input> \<textarea> \<select>
focus | get focus
14.2 SCRIPTING TEXT BOXES
texBox.value = "some new value";
: DO NOT use standard DOM methods(setAttribute…)
category | name | description |
---|---|---|
selection | textbox.select() | select all text when getting focus |
selectionStart selectionEnd |
textbox.value.substring(textbox.selectionStart, textbox.selectionEnd) |
|
setSelectionRange(startIndex, endIndex) | ||
filter | addHandler(“keypress”, func) | combine keypress and preventDefault |
Clipboard | beforecopy copy beforecut cut beforepaste paste |
|
event.clipboardData.getData("text") event.clipboardData.clearData() event.clipboardData.setData("text", "abcd") |
||
HTML5 Constraint Validation | required | |
type=”email” type=”url” |
input types | |
type=”number” (range, datetime, datetime-local, date, month, week, time) input.setUp(5) input.setDown(5) |
numeric ranges | |
checkValidity() | input.checkValidity() | |
input.validity | validation info | |
novalidate | <form method="post" novalidate> |
14.3 SCRIPTING SELECT BOXES
select element methods
method | description |
---|---|
add(newOption, relOption) | add newOption before relOption |
multiple | if multiple selection allowed boolean |
options | An HTMLCollection of <option> elements |
remove(index) | |
selectedIndex | |
size |
option element methods
method | description |
---|---|
index | |
label | |
selected | boolean |
text | |
value |
14.4 FORM SERIALIZATION
How serialize?
- Read through all fields then encode it as “name=abc&age=14&phone=123”
new FormData()
14.5 RICH TEXT EDITING
Skip
Chapter15 Graphics with Canvas
Skip
Chapter 16 HTML5 Scripting
16.1 CROSS-DOCUMENT MESSAGING (XDM)
Definition: the ability to pass information between pages from different origins
e.g. www.wrox.com
wants to communicate with a page from p2p.wrox.com
1 | //sender |
16.2 NATIVE DRAG AND DROP
Drag-and-Drop Events
- dragstart
- drag
- dragend
Dragged over a valid drop target
- dragenter
- dragover
- dragleave
- drop
The dataTransfer Object
Attribute | Description |
---|---|
event.dataTransfer.getData() | |
event.dataTransfer.setData() | |
======================== | ============================== |
event.dataTransfer.dropEffect | which type of drop behaviors are allowed [‘none’, move’, ‘copy’, ‘link’] |
event.dataTransfer.effectAllowed | which dropEffect is allowed for the dragged item |
======================== | ============================== |
event.dataTransfer.addElement(element) | Adds an element to the drag operation |
event.dataTransfer.clearData(format) | |
event.dataTransfer.setDragImage(element, x, y) | Allows you to specify an image to be displayed under the cursor as the drag takes plac |
event.dataTransfer.types | A list of data types currently being stored |
graggable | <img src="smile.gif" draggable="false"> |
16.3 MEDIA ELEMENTS
Two new tag: \<video> \<audio>
Tag | Attribute |
---|---|
src | media source |
poster | an image URI to display while the video content is being loaded |
controls | display a UI component |
Properties:
- autoplay, buffered, bufferedBytes, bufferingRate, bufferingThrottled,
controls, currentLoop, currentSrc, currentTime, defaultPlaybackRate,
duration, ended, loop, muted, networkState,
paused, playbackRate, played, readyState, seekable,
seeking, src, start, totalBytes, videoHeight, videoWidth,
volume, - abort, canplay, canplaythrough, canshowcurrentframe, dataunavailable,
durationchange, emptied, empty, ended, error,
load, loadeddata, loadedmetadata, loadstart, pause,
play, playing, progress, ratechange, seeked,
seeking, stalled, timeupdate, volumechange, waiting
Methods:
- element.play()
- element.pause()
- element.canPlayType(): return true/false
- Audio():
var audio = new Audio()
16.4 HISTORY STATE MANAGEMENT
Issue: sometimes I open a new dialog by js and wanna close it by the Back
button
1 | // push state into history |
Chapter17 Error Handling and Debugging
17.1 BROWSER ERROR REPORTING
Skip: Introduce Developer Tool
17.2 ERROR HANDLING
17.2.1 try-catch-finally
Error | Types |
---|---|
Error | base type |
EvalError | exception when eval() |
RangeError | number is outside the bounds of its range |
ReferenceError | attempting to access a variable that doesn’t exist |
SyntaxError | |
TypeError | |
URIError | encodeURI() or decodeURI() |
17.2.2 Throwing Errors
1 | // all legal |
customized error
1 | function CustomError(message){ |
When?
- A good error-handling protocol ensures that the only errors that occur are the ones that you throw
- e.g.
1 | function process(values){ |
17.2.3 The error Event
Error even has event !!!
1 | window.onerror = function(message, url, line){ |
17.2.4 Error-Handling Strategies
17.2.5 Identify Where Errors Might Occur
- Type coercion errors
- Data type errors
- Communication errors
17.2.6 Distinguishing between Fatal and Nonfatal Errors
17.2.7 Log Errors to the Server
Soooooo smart. Each image will visit its url.
1 | function logError(sev, msg){ |
17.3 DEBUGGING TECHNIQUES
17.3.1 Logging Messages to a Console
- error(message)
- info(message)
- log(message)
- warn(message)
17.3.2 Logging Messages to the Page
never mind
17.3.3 Throwing Errors
throw new Error(xxx);
assert(condition, msg)
17.4 COMMON INTERNET EXPLORER ERRORS
Skip
Chapter18 XML in JavaScript
Skip
Chapter19 ECMAScript for XML
Skip
Chapter20 JSON
20.1 SYNTAX
type | example |
---|---|
Simple Values | “Hello World” |
Object | {“name”: “Nicholas”, “age”: 29} |
Arrays | [{..}, {..}] |
20.2 PARSING AND SERIALIZATION
20.2.1 The JSON Object
Method | Convert |
---|---|
JSON.stringify() | object -> JSON string |
JSON.parse() | JSON string -> object |
20.2.2 Serialization Options
Filtering Results
1
2
3
4
5JSON.stringify(object, ["title", "edition"])
JSON.stringify(object, function(key, value){
if (key === "xxx") {return undefined;}
return value;
}
String Indentation
JSON.stringify(object, null, 4); // indent as 4
The toJSON() Method
define a toJSON() method in object. e.g.
1
2
3
4
5
6var book = {"name":"Nicholas",
"age":16,
toJSON:function() {
return this.name;
}}
JSON.stringify(book); // only stringify Simple Value name
20.2.3 Parsing Options
1 | var bookCopy = JSON.parse(jsonText, function(key, value){ |
Chapter21 Ajax and Comet
The key technology pushing Ajax forward was the XMLHttpRequest
(XHR) object
21.1 THE XMLHttpRequest OBJECT
21.1.2 XHR Usage
1 | var xhr = new XMLHttpRequest(); |
You can access only URLs that exist on the same origin, which means the same domain, using the same port, and with the same protocol.
readyState | description |
---|---|
0 | Uninitialized. The open() method hasn’t been called yet. |
1 | Open. The open() method has been called but send() has not been called. |
2 | Sent. The send() method has been called but no response has been received. |
3 | Receiving. Some response data has been retrieved. |
4 | Complete. All of the response data has been retrieved and is available. |
attribute | description |
---|---|
responseText | The text that was returned as the body of the response. |
responseXML | Contains an XML DOM document with the response data if the response has a content type of “text/xml” or “application/xml” . |
status | The HTTP status of the response. |
statusText | The description of the HTTP status. |
21.1.3 HTTP Headers
1 | xhr.open("get", "example.php", true); |
- Accept
- Accept-Charset
- Accept-Encoding
- Accept-Language
- Connection
- Cookie
- Host
- Referer
- User-Agent
21.1.4 GET Requests
1 | xhr.open("get", "example.php?name1=value1&name2=value2", true); // wrong |
21.1.5 POST Requests
1 | xhr.open("post", "postexample.php", true); |
- set header
- serialize form
21.2 XMLHttpRequest LEVEL 2
21.2.1 FormData
1 | var data = new FormData(); |
21.2.2 Timeouts
1 | xhr.open("get", "timeout.php", true); |
21.2.3 overrideMimeType()
The returned MIME type for a response determines how the response is handled by the XHR objec
1 | var xhr = createXHR(); |
21.3 PROGRESS EVENTS
event | description | |
---|---|---|
loadstart | Fires when the fi rst byte of the response has been received. | |
progress | Fires repeatedly as a response is being received. | lengthComputable, position, totalSize |
error | Fires when there was an error attempting the request. | |
abort | Fires when the connection was terminated by calling abort() . | |
load | Fires when the response has been fully received. | |
loadend | Fires when the communication is complete and after fi ring error , abort , or load . |
21.4 CROSS-ORIGIN RESOURCE SHARING
CORS: XHR objects can access resources only on the domain from which the containing web page originates
- send request with extra header called Origin including (protocol, domain name, and port)
- e.g.
Origin: http://www.nczonline.net
- e.g.
- If the server decides that the request should be allowed, it sends an
Access-Control-Allow-Origin
header echoing back the same origin that was sent or “*” if it’s a public resource- e.g.
Access-Control-Allow-Origin: http://www.nczonline.net
- e.g.
1 | var xhr = createXHR(); |
Preflighted Requests
- CORS allows the use of custom headers, methods other than GET or POST, and different body content types
- When you try to make a request with one of the advanced options, a “preflight” request is made to the server.
This request uses the OPTIONS method and sends the following headers
1
2
3Origin: http://www.nczonline.net
Access-Control-Request-Method: POST
Access-Control-Request-Headers: NCZserver should return
1
2
3
4Access-Control-Allow-Origin: http://www.nczonline.net
Access-Control-Allow-Methods: POST, GET
Access-Control-Allow-Headers: NCZ
Access-Control-Max-Age: 1728000
- Credentialed Requests
Access-Control-Allow-Credentials: true
21.5 ALTERNATE CROSS-DOMAIN TECHNIQUES
Image Pings
1
2
3
4
5var img = new Image();
img.onload = img.onerror = function(){
alert("Done!");
};
img.src = "http://www.example.com/test?name=Nicholas";
* you can only send GET requests
* you cannot access the response text from the server.
JSONP
1
2
3
4
5
6
7function handleResponse(response){
alert("You’re at IP address " + response.ip + ", which is in " +
response.city + ", " + response.region_name);
}
var script = document.createElement("script");
script.src = "http://freegeoip.net/json/?callback=handleResponse";
document.body.insertBefore(script, document.body.firstChild);- Unsafe: you’re pulling executable code into your page from another domain
- Hard to determine that a JSONP request has failed
Comet
- long polling
- streaming
Server-Sent Events
Client API for Comet
1
2
3
4
5
6
7var evtSource = new EventSource("ssedemo.php");
evtSource.onmessage = function(e) {
var newElement = document.createElement("li");
newElement.innerHTML = "message: " + e.data;
eventList.appendChild(newElement);
}Server code
1
2
3
def stream():
return Response(event(), mimetype="text/event-stream") # MIME type
Web Sockets
- Must use a specialized server supporting the protocol to work properly
Client API
- event: open, error, close, message
readyState
- WebSocket.OPENING(0)
- WebSocket.OPEN(1)
- WebSocket.CLOSING(2)
- WebSocket.CLOSE(3)
1
2
3
4
5
6
7
8var socket = new WebSocket("ws://www.example.com/server.php");
socket.send(JSON.stringify(message));
socket.onmessage = function(event) {
var data = event.data;
}
socket.close()
21.5.6 SSE versus Web Sockets
SSE
- base on HTTP protocol
- easier to implement
- one direction
Web Sockets
- base on Web Socket protocol
- bidirection
21.6 SECURITY
- Requiring SSL to access resources that can be requested via XHR.
- Requiring a computed token to be sent along with every request.
Chapter22 Advanced Techniques
22.1 ADVANCED FUNCTIONS
22.1.1 Safe Type Detection
Issue:
The instanceof
operator does not work when multiple global scopes are present, such as when there are multiple frames. e.g.var isArray = value instanceof Array;
Solution:
1 | function isArray(value){ |
22.1.2 Scope-Safe Constructors
1 | function Person(name, age, job){ |
22.1.3 Lazy Loading Functions
manipulating the function the first time it is called
1
2
3
4
5
6
7
8
9
10
11
12
13function createXHR(){
if (typeof XMLHttpRequest != "undefined"){
createXHR = function(){ // override the function
return new XMLHttpRequest();
};
}
else {
createXHR = function(){ // override the function
throw new Error("No XHR object available.");
};
}
return createXHR(); // next time the function is already decided
}assign the appropriate function immediately when the function is declared
1
2
3
4
5
6
7
8
9
10
11
12var createXHR = (function(){
if (typeof XMLHttpRequest != "undefined"){
return function(){
return new XMLHttpRequest();
};
}
else {
return function(){
throw new Error("No XHR object available.");
};
}
})();
22.1.4 Function Binding
see 5.5.5
22.1.5 Function Currying
Creates functions that have one or more arguments already set (also called partial function application
1 | var handler = { |
Just like functional programming
22.2 TAMPER-PROOF OBJECTS
Nonextensible Objects
- cannot add
Object.isExtensible(person)
1
2
3
4var person = { name: "Nicholas" };
Object.preventExtensions(person);
person.age = 29;
alert(person.age); //undefined
Sealed Objects
- cannot add/delete
Object.isSealed(person);
1
2
3
4
5
6
7var person = { name: "Nicholas" };
Object.seal(person);
person.age = 29;
alert(person.age); //undefined
delete person.name;
alert(person.name); //"Nicholas"
Frozen Objects
- cannot add/delete/update
Ojbject.isFrozen(person)
1
2
3
4
5
6
7
8
9
10var person = { name: "Nicholas" };
Object.seal(person);
person.age = 29;
alert(person.age); //undefined
delete person.name;
alert(person.name); //"Nicholas"
person.name = "Greg";
alert(person.name); //"Nicholas"
22.3 ADVANCED TIMERS
22.3.1 setTimeout and setInterval
- No code is executed immediately in JavaScript; it is executed as soon as the process is idle.
setTimeout(func, 250)
means adding func into the queue after 250mmsetInterval()
has 2 main issues:- intervals may be skipped
- intervals may be smaller than expected between multiple timer-code executions
Solution:
1 | setTimeout(function(){ |
22.3.2 Yielding Process
Issue:
- There is a long-running script limit
- If you reach that limit, the user is presented with a browser error dialog indicating that a script is taking too long to execute and asking whether the user would like to allow it to continue processing or stop.
Solution:
- array chunking
- create a queue of items to process, use timers to pull the next item to process, process it, and then set another timer
1 | setTimeout(function(){ |
22.3.3 Function Throttling
Issue:
- Attempting to perform too many DOM-related operations in sequence can cause the browser to hang, and sometimes crash.
Solution:
- The basic idea behind function throttling is that some code should not be executed repeatedly without a break
1 | var processor = { |
22.4 CUSTOM EVENTS
Use the observer pattern
22.5 DRAG AND DROP
just some drag/drop event implementation code
Chapter23 Offline Applications and Client-Side Storage
23.1 OFFLINE DETECTION
navigator.online
- events
online
offline
23.2 APPLICATION CACHE
Need a manifest file: lists out the resources to be downloaded
offline.appcache
1
2
3
4CACHE MANIFEST
file.js
file.css
The manifest file is associated with a page by specifying its path in the manifest attribute of
<html manifest="/offline.appcache">
JS API
- applicationCache.status
- applicationCache.update()
- applicationCache.swapCache()
- applicationCache event
- checking
- error
- noupdate
- downloading
- progress
- updateready
- cached
23.3 DATA STORAGE
23.3.1 Cookie
Response header:
1
2
3
4HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: name=value
Other-header: other-header-valueRequest header
1
2
3GET /index.html HTTP/1.1
Cookie: name=value
Other-header: other-header-value
- Restrictions
- Cookies are, by nature, tied to a specific domain
- Limitation of amount of cookies
- Limitation of length of cookies
Cookie Parts
- name: case insensitive, should be URL encoded
- value: should be URL encoded
- domain: The domain for which the cookie is valid
- path: The path within the specified domain for which the cookie should be sent to the server
- we can specify
http://www.wrox.com/books
as path, so cookie won’t be sent inhttps://www.wrox.com
even they have the same domain
- we can specify
- expiration: A time stamp indicating when the cookie should be deleted (that is, when it should stop being sent to the server
- secure flag: cookie information is sent to the server only if an SSL connection is used.
https://www.wrox.com
workshttp://www.wrox.com
doesn’t work
Cookie in JavaScript
document.cookie = "name=Nicholas"
- added to the existing set of cookies instead of
- Setting
document.cookie
does not overwrite any cookies unless the name of the cookie being set is already in use
Subcookies
- A technique that get around the per-domain cookie limit imposed by browsers
- format:
name=name1=value1&name2=value2&name3=value3&name4=value4&name5=value5
23.3.2 Internet Explorer User Data
Skip
23.3.3 The Storage Type
Storage Object
- methods
- clear()
- getItem(name)
- key(index)
- removeItem(name)
- setItem(name value)
- types
- sessionStorage
- globalStorage (deprecated)
- localStorage
- storage event
- Whenever a change is made to a Storage object, the storage event is fired on the document
- domain
- key
- newValue
- oldValue
sessionStorage
- Data is stored until the browser is closed
- Data stored persists across page refreshes
- Data available if the browser crashes and is restarted
localStorage
- In order to access the same localStorage object, pages must be served from the same domain (subdomains aren’t valid), using the same protocol, and on the same port.
- Data persisted until it is specifically removed via JavaScript or the user clears the browser’s cache.
23.3.4 IndexedDB
- database in JS
- use case
- store large amount of data in UI
- locate data fast
- suppport transaction
- offline application
Chapter24 Best Practices
- Maintainability
- Performance
- Deployment
Chapter25 Emerging APIs
25.1 requestAnimationFrame()
Reason:
- We need to determine the best way to schedule a redraw since each browser has a fixed refresh rate. So Javascript animation can work smoothly.
- setInterval() and setTimeout() are inaccurate.
- Redrawing too often will consume too much resource.
- This technique asks browser to update animation on next repaint.
Implementation:
Function | Description |
---|---|
setInterval() | Deprecated because of accuracy |
mozRequestAnimationFrame() | Chrome: webkitRequestanimationFrame(callback, element) IE: msRequestAnimationFrame() |
25.2 Page Visibility API
Reason:
- Knowing when users are actually interacting with the page.
Implementation
Function | Description |
---|---|
document.hidden | A Boolean value indicating if the page is hidden from view |
document.visibilityState | State indicator |
visibilitychange | Event fires when a document changes from hidden to visible or vice versa. |
25.3 Geolocation API
navigator.geolocation has 3 functions:
- getCurrentPosition(successCallBack, failCallback, options)
- successCallBack: latitude, longitude, accuracy, altitude, altitudeAccuracy, heading, speed
- options: enableHighAccuracy, timeout, maximumAge
- watchPosition()
- clearPosition()
25.4 File API
File Attributes
- name
- size
- type
- lastModifiedData
25.4.1 FileReader
Function | Description |
---|---|
readAsText(file, encoding) | store as plain text |
readAsDataURL(file) | store as URI |
readAsBinaryString(file) | store as Binary String |
readAsArrayBuffer(file) | store as ArrayBuffer |
Asynchronously:
Event | Description |
---|---|
progress | lengthComputable, loaded, total |
load | |
error | reader.error.code: 1, 2, 3, 4 |
25.4.2 Partial Reads
- Reason: Save time if read only parts of a file instead of the whole file
- Implementation:
blob.slice(startByte, length)
reader.readAsText(blobSliceObj)
25.4.3 Object URLs
- Reason: Don’t need to read the file contents into JavaScript in order to use them
Implementation:
1
2url = createObjectURL(file)
xx.innerHTML = `<img src="${url}">`
25.4.4 Drag-and-Drop File Reading
In event handler:
- Cancel the default behavior of dragenter, dragover, and drop.
event.dataTransfer.files
25.4.5 File Upload with XHR
1 | (in event handler) |
25.5 Web Timing
Reason: value page performance
25.6 Web Workers
Reason: allow uds to run asynchronous JavaScript that will not block the user interface
Implementation:
Page:
1
2
3
4
5
6var data = [1, 2, 3, 4];
var worker = new Worker("xx.js");
woder.onmessage = function(event) {
var data = event.data; // Formatted return data
}
worker.postmessage(data);xx.js(worker):
1
2
3
4
5self.onmessage = function(event) {
var data = event.data;
data.sort();
self.postMessage(data);
}Other functions:
Function | Description |
---|---|
worker.terminate() | stop worker in page |
self.close() | stop working in xx.js |
importScripts() | import script in xx.js |