js essence

69
JavaScript

Upload: uladzimir-piatryka

Post on 08-May-2015

1.964 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: JS Essence

JavaScript

Page 2: JS Essence

Get acquainted

Page 3: JS Essence

TargetProcess

Page 4: JS Essence

TP2 - Rich UI

Page 5: JS Essence

TP2 - Rich UI

Page 6: JS Essence

TP3 - high-performance UI

Page 7: JS Essence

Goals

• JS popularization• JS as engineering tool

Page 8: JS Essence

JS Phenomena

Page 9: JS Essence

Roadmap

• Embedded JS issues:- bad parts, good parts- imperative skin upon functional nature- misunderstanding of prototype inheritance- missing modules support- performance issues

Page 10: JS Essence

Bad parts, good parts

Page 11: JS Essence

Bad parts

• global variables• eval• a++• math• with• new (Number | String | Boolean)• == vs ===

Page 12: JS Essence

Good parts

• === : type safe vs (==)• [] : new Array()• {} : new Object()• a && b : if (a) b else a• a || b : if (a) a else b• closures (~ lambda curring)

Page 13: JS Essence

Java(??!)Script

Page 14: JS Essence

Java(??!)Script

• ..one more LISP dialect..• Mocha• LiveScript• JavaScript

Page 15: JS Essence

Programming paradigms

Page 16: JS Essence

Functional nature

• functions are the 1-st class objects:- assign to variables- pass as an argument- return as a result

Page 17: JS Essence

Inheritance?

Why?

Page 18: JS Essence

OOP in JavaScript

• Объект_о-ориентированный• Объектно-ориентированный

Page 19: JS Essence

Prototype chain

Page 20: JS Essence

Classical OOP simulation

• Classical OOP inheritance can be simulated:> I would recommend John Resig’s “Class” object http://ejohn.org/blog/simple-javascript-inheritance/

Page 21: JS Essence

Classical OOP simulation

Class.extend({init: function(a, b) {

// .ctorthis._super(a, b);

},method1: function() {

// do something}

});

Page 22: JS Essence

Inheritance examples

• Some examples

Page 23: JS Essence

Inheritance examples

var F = function(n) {this.name = n;

}var a = new F(“a”);var b = new F(“b”);

Page 24: JS Essence

Inheritance examples

var F = function(n) {this.name = n;

}F.prototype = { root: “hello world!” };var a = new F(“a”);var b = new F(“b”);a.root // ???b.root // ???

Page 25: JS Essence

Inheritance examples

var F = function(n) {this.name = n;

}F.prototype = { root: “hello world!” };var a = new F(“a”);var b = new F(“b”);

a.root = “Prototype inheritance magic”;b.root // ???

Page 26: JS Essence

Inheritance examples

var F = function() {}

var a = new F();a.constructor === F // ???

Page 27: JS Essence

Inheritance examples

var F = function() {}F.prototype = { root: “hello world!” };var a = new F();a.constructor === F // ???

Page 28: JS Essence

Dynamic inheritancevar F = function() {};F.prototype = {

count: 0,augment: function() {

++F.prototype.count;F.prototype.test = function() { alert(this.count) }

}};var a = new F();var b = new F();

a. augment();

a.test() // ???b.test() // ???

Page 29: JS Essence

Functions

• apply• call

Page 30: JS Essence

Modules

Page 31: JS Essence

Modules simulation

• No modules. Global variables RULEZZZ!!11

Page 32: JS Essence

Modules simulation

• No modules. Global variables RULEZZZ!!11

BAD!

Page 33: JS Essence

Modules simulation

• No named modules. BUT functional context

(function(global) { . . .})(window)

Page 34: JS Essence

Modules simulation

• No named modules. BUT functional context

(function(global) { . . .})(window)

Page 35: JS Essence

Modules simulation

• No named modules. BUT functional context

(function(global) { . . .})(window)

var myJQueryVar = $.noConflict()

Page 36: JS Essence

Modules simulation

• Namespacing as global variables chainsnewsite.common.utilsnewsite.common.services

var newsite = newsite || {};newsite.common = newsite.common || {};newsite.common.utils = function() { … };

Page 37: JS Essence

Modules simulation

• Namespacing as global variables chainsnewsite.common.utilsnewsite.common.services

• $LAB .script(“newsite.core.js").wait()

.script(“newsite.common.utils.js")

.script(“newsite.common.services.js“)

.wait(function() { /* ready */ })

Page 38: JS Essence

Modules simulation

RequireJShttp://requirejs.org/

Page 39: JS Essence

Modules simulation - RequireJS<!DOCTYPE html>

<html>

<head>

<title>My Sample Project</title>

<script

src="path_to/require.js“

data-main="entry_points/main">

</script>

</head>

<body>

<h1>My Sample Project</h1>

</body>

</html>

Page 40: JS Essence

entry_points/main.js

require([“dir/module1“, “dir/module2“],function(m1, m2) { /* to do: … */ }

);

Page 41: JS Essence

dir/module1.js

define([“dependency-on-some-other-modules”],function () {

return {color: "black",clear: function() {…}

};}

);

Page 42: JS Essence

Performance

Page 43: JS Essence

IE6?!

Page 44: JS Essence

Performance - prologue

• It’s still possible to write slow JavaScript on the new fast JavaScript engines

• JavaScript performance directly affects user experience

Page 45: JS Essence

High Performance JavaScript

Page 46: JS Essence

Performance

• Loading & execution• DOM scripting

Page 47: JS Essence

Loading and execution

• Most browsers use a single UI thread for UI updates and JavaScript execution

• Appearance of a <script ..> tag cause page download and rendering to stop and wait for the script to complete before processing

• Even parallel script downloads block downloading other resources (images, CSS)

Page 48: JS Essence

Loading and execution

• Put <script> tags as close to the bottom of the <body> as possible

• Load scripts in groups(100 kb faster than 4 x 25kb)

• Minify your scripts• Optimize your stylesheets

Page 49: JS Essence

Non-blocking loading

• <script defer> (IE 4+, FF 3.5+)• Dynamic <script> elements– Parallel non-blocking loading– Put into <head> to prevent “operation aborted”– Remember of ordering (cross-browser variation)

• XMLHttpRequest injection– Inline <script> vs eval()– Downloading from CDNs impossible

Page 50: JS Essence

RequireJS DO all the job!

Page 51: JS Essence

DOM Scripting

• Live DOM collections• Repaint and Reflow• Handling DOM events

Page 52: JS Essence

What is DOM?

• Document Object Model – language independent application interface (API) for working with XML and HTML documents

• Browsers keep DOM and JavaScript implementations independent of each other

Page 53: JS Essence

Toll bridge• Touch the DOM lightly• Stay within ECMAScript as much as possible

Page 54: JS Essence

HTML collections

• Expensive live collections• Use local variables when accessing collection

elements

Page 55: JS Essence

Repaints and reflows

• DOM tree• Render tree

Page 56: JS Essence

Reflow process

When a DOM tree change affects element geometry – browser recalculate geometry and position of elements that could have been affected by the change and reconstructs the Render tree

Page 57: JS Essence

Redraw process

Once the reflow is complete, the browser redraws the affected parts of the screen

Page 58: JS Essence

When does a reflow happen?

• Page renders initially• Visible DOM elements are added or removed• Elements change position• Element change size (margin, padding, border,

width, height)• Content is changed (text or image with

different size)• Browser window is resized

Page 59: JS Essence

Queuing and flushing reflows

• Browsers optimize reflow by queuing changes and performing them in batches

• Never request layout information while it’s being changed

Page 60: JS Essence

Queuing and flushing reflows

• offsetX• scrollX• clientX• getComputedStyle (currentStyle in IE)

* X – Top, Left, Width, Height

Page 61: JS Essence

Minimizing repaints and reflows

• Combine multiple DOM and style changes into a batch and apply them once

Page 62: JS Essence

Batching DOM changes

• Take the element off of the document flow• Apply multiply changes• Bring the element back to the document

Page 63: JS Essence

Ways to modify the DOM off the document

• Hide, apply changes and show again• Use document fragment to build subtree

outside of the live DOM and then copy it to the document

• Copy the original element into an off-document node, modify the copy and replace original element when done

Page 64: JS Essence

Take elements out of the flow for animation

1. Use absolute positioning2. Animate the element3. When the animation is done, restore the

positioning

JQuery DO this job for you!

Page 65: JS Essence

Event delegation

• A lot of event handlers affects memory, performance and useless since user clicks 1 button of 100 for example

• Set event handler for container element and use event delegation

Page 66: JS Essence

Performance essence

• http://jsperf.com/

• http://www.developer.nokia.com/Community/Wiki/JavaScript_Performance_Best_Practices

Page 67: JS Essence

Patterns

• http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/

Page 68: JS Essence

How to move next

• Primary• Advanced• Meta-level

Page 69: JS Essence

How to move next

• http://habrahabr.ru/post/117838/