Vous êtes sur la page 1sur 32

Client-side

lifecycle,
HTML & DOM
PZI 2016/2017

The lifecycle overview


User

Server

Internet browser

Send an HTTP request


for that URL

Enter URL
or click on a link

Execute code (find a file,


3
access a database, or
contact other services)

Receive HTTP response,


parse the content and start page building,
4
send a new HTTP request for every
external resource (image, script, style)
Finish page building

Process HTTP request,


send HTTP response

Page building phase,


create HTML elements, build the DOM
execute mainline JS

nteract with the page


(mouse clicks, key 7
resses, mouse moves)
Update UI,
store data

Send HTTP request

Event
handling phase

Process HTTP request,

9send HTTP response

The page-building phase


Parse the HTML and build the DOM
(Document Object Model)
Parse the CSS
Execute mainline JavaScript code

HTML
HyperText Markup Language (HTML)
A markup language combines (XML,
XAML, LaTeX)
First-version Tim Berners Lee, 1993 CERN
Standard by W3C - current version 5.1
(2016)
https://www.w3.org/TR/2016/REC-html51< !D O CTYPE htm l>
20161101/
< htm l>
< head> < /head>
< body> < /body>
< /htm l>

HTML
Start tag

< elem ent attr1= "val1" attr2= "val2">


Elem ent content
Content
< /elem ent>

(any combination of text and/or


other elements)

End tag

Self-closing element

Attribute

< elem ent attr1= "val1" attr2= "val2"/>


Attribute Attribute
value
name

DTD (Document Type


Definition)
Specifies the rules for the markup
language, so that the browser knows how
to render the content correctly.
HTML 5:

< !D O C TY P Eh tm l>
HTML 4 strict:

< !D O C TYPEH TM L PU BLIC "-//W 3C //D TD H TM L


4.01//EN " "http://w w w .w 3.org/TR/htm l4/strict.dtd">
HTML 4 loose:
< !D O CTYPEH TM L PU BLIC "-//W 3C//D TD H TM L 4.01
Transitional//EN " "http://w w w .w 3.org/TR/htm l4/loose.dtd">

Page-building phase
User

1
Enter URL
or click on a link

Internet browser

Server

Send an HTTP request


for that URL

Execute code (find a file,


3
access a database, or
contact other services)

Page building phase,Parse


create HTML elements, HTML and
build the DOM
build the
execute mainline JS
DOM

Execute
JavaScript
code

DOM (Document Object


Model)
W3C standard that defines the interface
between the application and a document.
(https://www.w3.org/DOM/)
Using the DOM, the application can
dynamically interact (read and modify)
the document.
In an HTML document, DOM objects are
organized into a DOM tree.
DOM objects are usually also called
nodes!

<!DOCTYPE html>
<html>
<head>
<title>Web app lifecycle</title>
<style> #first { color: green; } #second { color: red; } </style>
</head>
<body>
<ul id="first"></ul>
<script>
Creates a new
function addMessage(element, message){
element,
const messageElement = document.createElement("li");
messageElement.textContent = message;
adds a text message
element.appendChild(messageElement);
to it,
}

and appends it to
const first = document.getElementById("first");
Adds a message
the passed in
addMessage(first, "Page loading");
that a page
is
element.
</script>
loading
<ul id="second"></ul>

<script>
When a mouse
document.body.addEventListener("mousemove", function() {
moves,
addMessage(document.getElementById("second"), "Event: mousemove");
});
add a mouse

move message
document.body.addEventListener("click", function(){
When the page is
addMessage(document.getElementById("second"), "Event: click");
});
clicked,
</script>
add the click
</body>
message
</html>

1
<!DOCTYPE html>
1 <html>
html
2 <head>
4
3 <title>Web app lifecycle</title> 2
7
5 <style>
head
body
#first
{
color:
green;
}
6
5 8
9
#second { color: red; } 3
</style>
style
title
ul script
</head>
7 <body>
Web app
#first
function
8 <ul id="first"></ul>
4 lifecylce
6 {}
addMessage
9 <script>
#second{
}
function addMessage(element, message){
const messageElement =
document.createElement("li");
messageElement.textContent = message;
element.appendChild(messageElement);
}

HTML is a blueprint for


DOM construction (the
browser can fix)
<html>
<head>
<p>Hello</p>
</head>
<body>
</body>
</html>
ERROR!
Content
elements
should not be
contained
within the
head element

html

html
head
p

body

head

body
p

The DOM as specified The DOM constructed


by HTML code
by the browser

DOM relationships
A
B
E

C
txt

A - root node/element
B, C, D - children of A
B firstChild of A, D lastChild of A
A - parentNode of B, C, D
B, C, D are siblings
C nextSibling of B, C previousSibling of D
B, C, D, E, txt - descendants of A
A - ancestor of B, C, D, E, txt
E - children of B; E, txt - childNodes of B

A, B, C, D, E - HTML elements
A, B, C, D, E, txt - HTML nodes
children (only elements); childNodes (elements and text)

DOM traversal through


relationships
B.childN odes; //[txt1, E, txt2, F]
B.children;
//[E, F]
B.fi
rstChild; //txt1
B.fi
rstElem entChild; //E
B.lastChild; //F
txt1
B.lastElem entChild; //F
E.nextSibling; //txt2
E.nextElem entSibling; //F

A
B
E

C
txt2

D
F

DOM standard (W3C)


DOM lvl 1 (1998) model for HTML,
access and manipulate DOM nodes
DOM lvl 2 (2000) CSS, events
DOM lvl 3 (2004) new events
(keyboard)
DOM lvl 4 (2015) feature detection,
event construction

Executing JavaScript code


JavaScript code contained in the
<script> element is executed by the
browser's JavaScript engine
Primary purpose to interact with the
page.
Interaction is done through global
objects.

Global objects
window - global object through which all other global objects,
global variables (even user-defined oness), and browser API-s
are accessible.
https://developer.mozilla.org/en-US/docs/Web/API/Window
<script>
window.parseInt(); //global function
parseInt();

//can be called without


//"window."

const a = 3;//Defines a global variable


window.a; //3 can be accessed through window
</script>

Globals: document object


document (or window.document)

(https://developer.mozilla.org/en-US/docs/Web/API/document)

Serves as an entry point to web page


content:
getElem entById, getElem entsByClassN am e,
getElem entsByTagN am e, getElem entsByN am e,
querySelector, querySelectorAll
w rite, w riteln (dont use!)
createElem ent

Globals: history object


history (or w indow .history)
https://developer.mozilla.org/enUS/docs/Web/API/Window/history

Interact with the history session ("go


back" button, programmatically add
intermediate states)

Globals: local storage


localStorage (or w indow .localStorage)
(https://developer.mozilla.org/enUS/docs/Web/API/Window/localStorage)
Stores string keys and string values.
A domain can store several MB of data
(3,Storage.
5, 10MB,
on the browser).
local
setItem ('depending
user', 'Tom ');
localStorage.getItem ('user'); //Tom
localStorage.setItem ('user', JSO N .stringify({
nam e: 'Tom '
})); //Store objects w ith JSO N .stringify
const person = JSO N .parse(localStorage.getItem ('user'));

Globals: location
Interact with the information about the
current URL of the page (reload, go to
new URL from JavaScript, access hash
data, protocol, search query)
https://developer.mozilla.org/enUS/docs/Web/API/Window/location

Globals: console
Object for logging information to the
browser's console
(https://developer.mozilla.org/enUS/docs/Web/API/Window/console)
console.log('M essage'); //Logs 'M essage'to the console
console.assert(truthy | falsy, 'M essage'); //Breaks if falsy
console.tim e('Som e-string-ID '); //Starts a tim er
console.tim eEnd('Som e-string-ID '); //Stops the tim er
//Prints out the result

Dynamically modifying the


DOM with JavaScript
Use:
docum ent.createElem ent("elem entN am e") to create
new elements (e.g. docum ent.createElem ent("p"))
elem ent.appendChild(otherElem ent) to

add a new

child to an element
elem ent.rem oveChild(child) to

remove a child of an

element
elem ent.textContent = "N ew Text" to

change the text

of an element;
elem ent.innerH TM L = "< p> Som e < b> H TM L< /b> < /p> "

to change the HTML of an element (changes


that subtree of the DOM)

HTML attributes
HTML attributes are additional values that
configure HTML elements or adjust their behavior.
< input type= "passw ord" < !-- Adjusts the behavior/look -->
id= "m yId" < !-- Allow s us to reference the elem ent -->
class= "m yClass" < !-- sets the class -->
data-custom -attribute= "m yAttribute"/> < !-- Custom -->

Interact with values:


directly:

elem ent.type //"passw ord"


elem ent.id
//"m yId"
elem ent.class //undefi
n ed, class keyw ord in JS
elem ent.classN am e //"m yC lass"
Cannot access custom attributes

through methods getAttribute and setAttribute


elem ent.getAttribute("id"), elem ent.getAttribute("class"),
elem ent.getAttribute("data-custom -attribute");

<!DOCTYPE html>
<html>
<head>
<title>Web app lifecycle</title>
<style> #first { color: green; } #second { color: red; }
</style>
</head>
<body>
The DOM tree can be modified to any degre
<ul id="first"></ul>
create new nodes, delete or modify existing
<script>
function addMessage(element, message){
const messageElement = document.createElement("li");
html
messageElement.textContent = message;
element.appendChild(messageElement);
}

head

const first = document.getElementById("first");


addMessage(first, "Page loading");
</script>
title

Web app

Even though an element is created,lifecylce


it won't be a part of the UI until
it's inserted into the DOM!

style
#first
{}
#second{
}

li
Page
loading

body
ul

script
function
addMessage

<!DOCTYPE html>
<html>
<head>
<title>Web app lifecycle</title>
<style> #first { color: green; } #second { color: red; } </style>
</head>
<body>
<ul id="first"></ul>
<script>
function addMessage(element, message){
const messageElement = document.createElement("li");
messageElement.textContent = message;
element.appendChild(messageElement);
}
const first = document.getElementById("first");
addMessage(first, "Page loading");
</script>
<ul id="second"></ul>

Building the DOM

<script>
document.body.addEventListener("mousemove", function() {
addMessage(document.getElementById("second"), "Event: mousemove");
});
document.body.addEventListener("click", function(){
addMessage(document.getElementById("second"), "Event: click");
});
</script>
Execute JavaScript code
</body>
</html>

Page building done


Once the page is built, the browser
reports two events:
D O M ContentLoaded (on docum ent) the
whole HTML code has been processed
load (on w indow , docum ent) the whole
HTML code has been processed and all
resources have been loaded

Careful!
Modifying the page is expensive (for a
large number of changes)
Changing a single node can have an
influence on how a lot of other nodes are
rendered.
(
https://www.youtube.com/watch?v=ZTnI
xIA5KGw
)
Also, beware of premature optimizations!
Use console.tim e to measure!

Example
Which is faster?
A: function alignBookm arksFirst(){
const readableElem ents = docum ent.querySelectorAll(".readable-text");
const bookm arks = docum ent.querySelectorAll(".fa-bookm ark-o");
for(let i= 0; i< readableElem ents.length; i+ + )
bookm arks[i].style.top = $(readableElem ents[i]).position().top + "px";
}

B: function alignBookm arksAndParagraphsSecond(){


const bookm arks = docum ent.querySelectorAll(".fa-bookm ark-o");
const readableElem ents = docum ent.querySelectorAll(".readable-text");
const positions = [];
for(let i= 0; i< readableElem ents.length; i+ + )
positions.push($(readableTextElem ent).position().top + "px");
for(let i= 0; i< bookm arks.length; i+ + )
bookm arks[i].style.top = positions[i];
}

Layout trashing
The browser tries to be lazy and batch
updates
Occurs when we don't allow the browser
to batch
updates:
const
h1 = element1.clientHeight;
//Read
element1.style.height = (h1 * 2) + 'px'; // Write (invalidates
layout)
const h2 = element2.clientHeight; // Read (triggers layout)
element2.style.height = (h2 * 2) + 'px'; // Write (invalidates
layout)
const h3 = element3.clientHeight; // Read (triggers layout)
element3.style.height = (h3 * 2) + 'px'; // Write (invalidates

Batch reads and writes


(whenever possible!)
const h1 = element1.clientHeight; // Read
const h2 = element2.clientHeight; // Read (triggers layout)
const h3 = element3.clientHeight; // Read (triggers layout)
element1.style.height = (h1 * 2) + 'px'; // Write (invalidates layout)
element2.style.height = (h2 * 2) + 'px'; // Write (invalidates layout)
element3.style.height = (h3 * 2) + 'px'; // Write (invalidates layout)

Layout invalidation
properties
Interface

Property name

Element

clientHeight, clientLeft, clientTop, clientWidth, focus,


getBoundingClientRect, getClientRects, innerText,
offsetHeight,
offsetLeft, offsetParent, offsetTop, offsetWidth,
outerText,
scrollByLines, scrollByPages, scrollHeight,
scrollIntoView,
scrollIntoViewIfNeeded, scrollLeft, scrollTop,
scrollWidth

MouseEvent
Window
Frame,
Document,
Image

layerX, layerY, offsetX, offset


getComputedStyle, scrollBy, scrollTo, scroll, scroll
height, width

Libraries that optimize


DOM manipulation
fastdom:
https://github.com/wilsonpage/fastdom
http
://wilsonpage.github.io/fastdom/examples/an
imation.html
http://wilsonpage.github.io/fastdom/examples
/aspect-ratio.html

React (http://facebook.github.io/react/)
Set of virtual objects that mimic the DOM
React code deals with the virtual DOM (plain

Vous aimerez peut-être aussi