JS
Event Loop, JavaScript in Browser,
DOM/BOM, Memory
Agenda
- Event loop
-
JavaScript in Browser
- DOM
- BOM
- Memory
Event Loop
Стек (Stack)
Вызов любой функции создает контекст выполнения. При вызове вложенной функции создается новый контекст, а старый сохраняется в специальной структуре. Так формируется стек контекстов.
Очередь (Queue)
Среда выполнения JavaScript содержит очередь событий. Очередь событий — это список событий, подлежащих обработке. Каждое событие ассоциируется с некоторой функцией. Когда на стеке освобождается достаточно места, событие извлекается из очереди и обрабатывается.
Event Loop
function multiply(a, b) {
return a * b;
};
function square(n) {
return multiply(n, n)
};
function printSquare(n) {
var squared = square(n);
console.log(squared);
};
printSquare(4);
Stack
main()
printSquare(4)
square(n)
multiply(n, n)
Call Stack
function foo(a, b) {
throw new Error('Oops!');
};
function bar(n) {
foo();
};
function baz(n) {
bar();
};
baz();
Call Stack
function foo() {
return foo();
}
foo();
main()
foo()
foo()
foo()
foo()
foo()
Call Stack
console.log('Hi');
setTimeout(function() {
console.log('There');
}, 5000);
console.log('All');
main()
Stack
webAPIs
Task Queue
timeout
event loop
hi
All
Call Stack
console.log('Hi');
setTimeout(function() {
console.log('There');
}, 5000);
console.log('All');
main()
Stack
webAPIs
Task Queue
timeout
event loop
All
hi()
Call Stack
console.log('Hi');
setTimeout(function() {
console.log('There');
}, 5000);
console.log('All');
main()
setTimeout(cb)
Stack
webAPIs
Task Queue
cb
timer()
cb
event loop
All
Call Stack
console.log('Hi');
setTimeout(function() {
console.log('There');
}, 5000);
console.log('All');
main()
Stack
webAPIs
Task Queue
cb
event loop
log('All')
console.log('Hi');
setTimeout(function() {
console.log('There');
}, 0);
console.log('All');
or
Call Stack
console.log('Hi');
setTimeout(function() {
console.log('There');
}, 5000);
console.log('All');
Stack
webAPIs
Task Queue
cb
event loop
Call Stack
console.log('Hi');
setTimeout(function() {
console.log('There');
}, 5000);
console.log('All');
Stack
webAPIs
Task Queue
event loop
cb
log('There')
Event Loop
The Call Stack
one thread == one call stack == one thing at a time
Call Stack Demos
function multiply(a, b) {
return a * b;
}
function square(n) {
return multiply(n, n);
}
function printSquare(n) {
var squared = square(n);
console.log(squared);
}
printSquare(4);
JavaScript in Browser
look a round
DOM
DOM
With the DOM, JavaScript gets all the power it needs to create dynamic HTML:
- JavaScript can change all the HTML elements in the page
- JavaScript can change all the HTML attributes in the page
- JavaScript can change all the CSS styles in the page
- JavaScript can remove existing HTML elements and attributes
- JavaScript can add new HTML elements and attributes
- JavaScript can react to all existing HTML events in the page
- JavaScript can create new HTML events in the page
DOM
//Retrieves the element with the given id as an object
document.getElementById('id');
//Retrieves all elements with the tag name tagname and stores them in an
//array like
document.getElementsByTagName('tagname');
//Retrieves the value of the attribute with the name attribute
node.getAttribute('attribute');
//Sets the value of the attribute with the name attribute to value
node.setAttribute('attribute', 'value');
//Reads the type of the node (1 = element, 3 = text node)
node.nodeType;
//Reads the name of the node (either element name or #textNode)
node.nodeName;
//Reads or sets the value of the node (the text content in the case of
//text nodes)
node.nodeValue;
Reaching Elements in a Document
Reading Element Attributes, Node Values and Other Data
Relations of element
Creating of node
el.innerHTML = "<div>Some text</div>" // :(
// :)
<div id="dom"></div>
var el = document.getElementById('dom');
var div = document.createElement('div');
var text = document.createTextNode('Text');
div.appendChild(text);
div.setAttribute('id', 'child');
el.appendChild(div);
// document.createDocumentFragment();
DOM
//Retrieves the previous sibling node and stores it as an object.
node.previousSibling;
//Retrieves the next sibling node and stores it as an object.
node.nextSibling;
//Retrieves all child nodes of the object and stores them in an list.
//here are shortcuts for the first and last child node, named node.
//firstChild and node.lastChild.
node.childNodes;
//Retrieves the node containing node.
node.parentNode;
Navigating Between Nodes
DOM
//Creates a new element node with the name element. You provide the name
//as a string.
document.createElement(element);
//Creates a new text node with the node value of string.
document.createTextNode(string);
//Creates newNode as a copy (clone) of node. If bool is true, the clone
//includes clones of all the child nodes of the original.
newNode = node.cloneNode(bool);
//Adds newNode as a new (last) child node to node.
node.appendChild(newNode);
//Inserts newNode as a new child node of node before oldNode.
node.insertBefore(newNode,oldNode);
//Removes the child oldNode from node.
node.removeChild(oldNode);
//Replaces the child node oldNode of node with newNode.
node.replaceChild(newNode, oldNode);
//Reads or writes the HTML content of the given element as a string—
//including all child nodes with their attributes and
//text content.
element.innerHTML;
Creating New Nodes
Mouse Events
onclick
The event occurs when the user clicks on an element
ondblclick
The event occurs when the user double-clicks on an element
onmousedown
The event occurs when a user presses a mouse button over an element
onmousemove
The event occurs when the pointer is moving while it is over an element
onmouseover
The event occurs when the pointer is moved onto an element
onmouseout
The event occurs when a user moves the mouse pointer out of an element
onmouseup
The event occurs when a user releases a mouse button over an element
Keyboard Events
onkeydown
The event occurs when the user is pressing a key
onkeypress
The event occurs when the user presses a key
onkeyup
The event occurs when the user releases a key
Handlers
addEventListener()
document.getElementById('cupcakeButton').addEventListener('click', getACupcake);
document.getElementById('cupcakeButton').attachEvent('onclick', getACupcake);
//Note: Internet Explorer 9 adds support for addEventListener().
Event object
event.target is the original element the event happened to. However, Internet Explorer calls it event. srcElement. In fact, Chrome and Safari started setting both. You can do this for maximum compatibility:
function getACupcake(event) {
var target = event.target || event.srcElement;
target.style.backgroundColor = '#F00'; // use it
}
BOM
The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.
- alert/confirm/prompt
- delayed execution (setTimeout, setInterval)
- Location
- Navigator
- Data storage (cookies/LocalStorage)
- Local/Session storage
- Dimensions
- ...
BOM
BOM
BOM
BOM
// you may set each of this properties, like
location.href = 'http://google.com'; // redirect to google.com
location.hash = '#11';
// this event fire when hash was changed
window.addEventListener('hashchange', function(e) {
console.log(e.oldURL + ' -> ' + e.newURL);
});
BOM
Navigator
Navigator object is used to detect client browser type.
Since earlier many sites support only Netscape - all browsers use 'Mozilla' as values for appName. This, actually, is written in standard, so this property is not very useful.
// get user-agent string, which can be parsed and detect browser.
navigator.userAgent;
// Array of installed plugins. May be used to detect installed plugins, like Adobe Flash
navigator.plugins;
// Current system language
navigator.language;
// If user allows you to track his position you may use geolocation to retrieve
// user current coordinates (HTML5)
navigator.geolocation.getCurrentPosition(success, error);
var positionChangeWatch = navigator.geolocation.watchPosition(success, error);
navigator.geolocation.clearWatch(positionChangeWatch);
Links
- https://developer.mozilla.org/ru/docs/Web/JavaScript/EventLoop
- https://learn.javascript.ru/events-and-timing-depth
- https://www.youtube.com/watch?v=8aGhZQkoFbQ
- https://learn.javascript.ru/document
- https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers
- https://developer.mozilla.org/en-US/docs/Web/API/Location
- https://developer.mozilla.org/en-US/docs/Web/API/Navigator
- https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Examples
js-event-loop_dom_bom
By Oleg Rovenskyi
js-event-loop_dom_bom
- 609