SlideShare une entreprise Scribd logo
1  sur  69
JavaScript
Get acquainted
TargetProcess
TP2 - Rich UI
TP2 - Rich UI
TP3 - high-performance UI
Goals
• JS popularization
• JS as engineering tool
JS Phenomena
Roadmap
• Embedded JS issues:
  - bad parts, good parts
  - imperative skin upon functional nature
  - misunderstanding of prototype inheritance
  - missing modules support
  - performance issues
Bad parts, good parts
Bad parts
•   global variables
•   eval
•   a++
•   math
•   with
•   new (Number | String | Boolean)
•   == vs ===
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)
Java(??!)Script
Java(??!)Script
•   ..one more LISP dialect..
•   Mocha
•   LiveScript
•   JavaScript
Programming paradigms
Functional nature
• functions are the 1-st class objects:
  - assign to variables
  - pass as an argument
  - return as a result
Inheritance?


Why?
OOP in JavaScript
• Объект_о-ориентированный
• Объектно-ориентированный
Prototype chain
Classical OOP simulation
• Classical OOP inheritance can be simulated:
  > I would recommend John Resig’s “Class”
  object
    http://ejohn.org/blog/simple-javascript-inheritance/
Classical OOP simulation
Class.extend({
    init: function(a, b) {
          // .ctor
          this._super(a, b);
    },
    method1: function() {
          // do something
    }
});
Inheritance examples
• Some examples
Inheritance examples
var F = function(n) {
  this.name = n;
}
var a = new F(“a”);
var b = new F(“b”);
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 // ???
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 // ???
Inheritance examples
var F = function() {}

var a = new F();
a.constructor === F // ???
Inheritance examples
var F = function() {}
F.prototype = , root: “hello world!” -;
var a = new F();
a.constructor === F // ???
Dynamic inheritance
var 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() // ???
Functions
• apply
• call
Modules
Modules simulation
• No modules. Global variables RULEZZZ!!11
Modules simulation
• No modules. Global variables RULEZZZ!!11



                 BAD!
Modules simulation
• No named modules. BUT functional context

       (function(global) { . . .})(window)
Modules simulation
• No named modules. BUT functional context

       (function(global) { . . .})(window)
Modules simulation
• No named modules. BUT functional context

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

       var myJQueryVar = $.noConflict()
Modules simulation
• Namespacing as global variables chains
    newsite.common.utils
    newsite.common.services

  var newsite = newsite || {};
  newsite.common = newsite.common || {};
  newsite.common.utils = function() , … -;
Modules simulation
• Namespacing as global variables chains
     newsite.common.utils
     newsite.common.services
• $LAB
     .script(“newsite.core.js").wait()
     .script(“newsite.common.utils.js")
     .script(“newsite.common.services.js“)
     .wait(function() { /* ready */ })
Modules simulation


   RequireJS
  http://requirejs.org/
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>
entry_points/main.js
require(
   *“dir/module1“, “dir/module2“+,
   function(m1, m2) { /* to do: … */ }
);
dir/module1.js
define(
   *“dependency-on-some-other-modules”+,
   function () {
       return {
             color: "black",
             clear: function() ,…-
       };
   }
);
Performance
IE6?!
Performance - prologue
• It’s still possible to write slow JavaScript on
  the new fast JavaScript engines

• JavaScript performance directly affects user
  experience
High Performance JavaScript
Performance
• Loading & execution
• DOM scripting
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)
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
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
RequireJS DO all the job!
DOM Scripting
• Live DOM collections
• Repaint and Reflow
• Handling DOM events
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
Toll bridge
• Touch the DOM lightly
• Stay within ECMAScript as much as possible
HTML collections
• Expensive live collections
• Use local variables when accessing collection
  elements
Repaints and reflows
• DOM tree
• Render tree
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
Redraw process
Once the reflow is complete, the browser
redraws the affected parts of the screen
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
Queuing and flushing reflows
• Browsers optimize reflow by queuing changes
  and performing them in batches
• Never request layout information while it’s
  being changed
Queuing and flushing reflows
•   offsetX
•   scrollX
•   clientX
•   getComputedStyle (currentStyle in IE)

* X – Top, Left, Width, Height
Minimizing repaints and reflows
• Combine multiple DOM and style changes into
  a batch and apply them once
Batching DOM changes
• Take the element off of the document flow
• Apply multiply changes
• Bring the element back to the document
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
Take elements out of the flow for
             animation
1. Use absolute positioning
2. Animate the element
3. When the animation is done, restore the
   positioning

          JQuery DO this job for you!
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
Performance essence
• http://jsperf.com/

• http://www.developer.nokia.com/Community
  /Wiki/JavaScript_Performance_Best_Practices
Patterns
• http://www.addyosmani.com/resources/esse
  ntialjsdesignpatterns/book/
How to move next
• Primary
• Advanced
• Meta-level
How to move next
• http://habrahabr.ru/post/117838/

Contenu connexe

Tendances

DSLs Internas e Ruby
DSLs Internas e RubyDSLs Internas e Ruby
DSLs Internas e RubyFabio Kung
 
Introduction to Programming (well, kind of.)
Introduction to Programming (well, kind of.)Introduction to Programming (well, kind of.)
Introduction to Programming (well, kind of.)Julie Meloni
 
QueryPath, Mash-ups, and Web Services
QueryPath, Mash-ups, and Web ServicesQueryPath, Mash-ups, and Web Services
QueryPath, Mash-ups, and Web ServicesMatt Butcher
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO DevsWO Community
 
Working with the django admin
Working with the django admin Working with the django admin
Working with the django admin flywindy
 
Comprehensive Browser Automation Solution using Groovy, WebDriver & Obect Model
Comprehensive Browser Automation Solution using Groovy, WebDriver & Obect ModelComprehensive Browser Automation Solution using Groovy, WebDriver & Obect Model
Comprehensive Browser Automation Solution using Groovy, WebDriver & Obect ModelvodQA
 
Learning About JavaScript (…and its little buddy, JQuery!)
Learning About JavaScript (…and its little buddy, JQuery!)Learning About JavaScript (…and its little buddy, JQuery!)
Learning About JavaScript (…and its little buddy, JQuery!)Julie Meloni
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleRaimonds Simanovskis
 
Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application Andy Bunce
 
Killing Shark-Riding Dinosaurs with ORM
Killing Shark-Riding Dinosaurs with ORMKilling Shark-Riding Dinosaurs with ORM
Killing Shark-Riding Dinosaurs with ORMOrtus Solutions, Corp
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Eric Palakovich Carr
 
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and CapabilitiesNot Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and CapabilitiesBrett Meyer
 
QueryPath: It's like PHP jQuery in Drupal!
QueryPath: It's like PHP jQuery in Drupal!QueryPath: It's like PHP jQuery in Drupal!
QueryPath: It's like PHP jQuery in Drupal!Matt Butcher
 
The Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQueryThe Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQuerycolinbdclark
 
User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014Robert Stupp
 
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...Sencha
 
Extending Oracle E-Business Suite with Ruby on Rails
Extending Oracle E-Business Suite with Ruby on RailsExtending Oracle E-Business Suite with Ruby on Rails
Extending Oracle E-Business Suite with Ruby on RailsRaimonds Simanovskis
 

Tendances (20)

Practical JRuby
Practical JRubyPractical JRuby
Practical JRuby
 
DSLs Internas e Ruby
DSLs Internas e RubyDSLs Internas e Ruby
DSLs Internas e Ruby
 
Introduction to Programming (well, kind of.)
Introduction to Programming (well, kind of.)Introduction to Programming (well, kind of.)
Introduction to Programming (well, kind of.)
 
QueryPath, Mash-ups, and Web Services
QueryPath, Mash-ups, and Web ServicesQueryPath, Mash-ups, and Web Services
QueryPath, Mash-ups, and Web Services
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
 
Working with the django admin
Working with the django admin Working with the django admin
Working with the django admin
 
Comprehensive Browser Automation Solution using Groovy, WebDriver & Obect Model
Comprehensive Browser Automation Solution using Groovy, WebDriver & Obect ModelComprehensive Browser Automation Solution using Groovy, WebDriver & Obect Model
Comprehensive Browser Automation Solution using Groovy, WebDriver & Obect Model
 
Learning About JavaScript (…and its little buddy, JQuery!)
Learning About JavaScript (…and its little buddy, JQuery!)Learning About JavaScript (…and its little buddy, JQuery!)
Learning About JavaScript (…and its little buddy, JQuery!)
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application
 
Killing Shark-Riding Dinosaurs with ORM
Killing Shark-Riding Dinosaurs with ORMKilling Shark-Riding Dinosaurs with ORM
Killing Shark-Riding Dinosaurs with ORM
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and CapabilitiesNot Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
 
Object Oriented JavaScript - II
Object Oriented JavaScript - IIObject Oriented JavaScript - II
Object Oriented JavaScript - II
 
QueryPath: It's like PHP jQuery in Drupal!
QueryPath: It's like PHP jQuery in Drupal!QueryPath: It's like PHP jQuery in Drupal!
QueryPath: It's like PHP jQuery in Drupal!
 
The Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQueryThe Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQuery
 
User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014
 
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
 
Extending Oracle E-Business Suite with Ruby on Rails
Extending Oracle E-Business Suite with Ruby on RailsExtending Oracle E-Business Suite with Ruby on Rails
Extending Oracle E-Business Suite with Ruby on Rails
 
XQuery in the Cloud
XQuery in the CloudXQuery in the Cloud
XQuery in the Cloud
 

En vedette

版本控制与常见的分支模型
版本控制与常见的分支模型版本控制与常见的分支模型
版本控制与常见的分支模型Tony Deng
 
Mobile Disrupts the Cloud
Mobile Disrupts the CloudMobile Disrupts the Cloud
Mobile Disrupts the CloudDreamFactory
 
Trans cold express 6 page overview
Trans cold express 6 page overviewTrans cold express 6 page overview
Trans cold express 6 page overviewGreg Kirchner
 
SEE Opportunity Mobile Application Development
SEE Opportunity Mobile Application Development SEE Opportunity Mobile Application Development
SEE Opportunity Mobile Application Development Rea Dione
 
Learn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionLearn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionIn a Rocket
 

En vedette (7)

版本控制与常见的分支模型
版本控制与常见的分支模型版本控制与常见的分支模型
版本控制与常见的分支模型
 
Mobile Disrupts the Cloud
Mobile Disrupts the CloudMobile Disrupts the Cloud
Mobile Disrupts the Cloud
 
Trans cold express 6 page overview
Trans cold express 6 page overviewTrans cold express 6 page overview
Trans cold express 6 page overview
 
Streams
StreamsStreams
Streams
 
Components now!
Components now! Components now!
Components now!
 
SEE Opportunity Mobile Application Development
SEE Opportunity Mobile Application Development SEE Opportunity Mobile Application Development
SEE Opportunity Mobile Application Development
 
Learn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionLearn BEM: CSS Naming Convention
Learn BEM: CSS Naming Convention
 

Similaire à JS Essence

Masterin Large Scale Java Script Applications
Masterin Large Scale Java Script ApplicationsMasterin Large Scale Java Script Applications
Masterin Large Scale Java Script ApplicationsFabian Jakobs
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoFu Cheng
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Doris Chen
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)Doris Chen
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbMongoDB APAC
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Top 8 Improvements in Drupal 8
Top 8 Improvements in Drupal 8Top 8 Improvements in Drupal 8
Top 8 Improvements in Drupal 8Angela Byron
 
Modernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul JonesModernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul JonesiMasters
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and ActivatorKevin Webber
 
JavaScript performance patterns
JavaScript performance patternsJavaScript performance patterns
JavaScript performance patternsStoyan Stefanov
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS偉格 高
 
Django Overview
Django OverviewDjango Overview
Django OverviewBrian Tol
 
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD CombinationLotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD CombinationSean Burgess
 
Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011Timothy Fisher
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedGil Fink
 
JavaScript!
JavaScript!JavaScript!
JavaScript!RTigger
 

Similaire à JS Essence (20)

Masterin Large Scale Java Script Applications
Masterin Large Scale Java Script ApplicationsMasterin Large Scale Java Script Applications
Masterin Large Scale Java Script Applications
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
 
jQuery Objects
jQuery ObjectsjQuery Objects
jQuery Objects
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
Buildingsocialanalyticstoolwithmongodb
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Top 8 Improvements in Drupal 8
Top 8 Improvements in Drupal 8Top 8 Improvements in Drupal 8
Top 8 Improvements in Drupal 8
 
Modernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul JonesModernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul Jones
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and Activator
 
JavaScript performance patterns
JavaScript performance patternsJavaScript performance patterns
JavaScript performance patterns
 
XPages Performance Master Class - Survive in the fast lane on the Autobahn (E...
XPages Performance Master Class - Survive in the fast lane on the Autobahn (E...XPages Performance Master Class - Survive in the fast lane on the Autobahn (E...
XPages Performance Master Class - Survive in the fast lane on the Autobahn (E...
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
 
Django Overview
Django OverviewDjango Overview
Django Overview
 
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD CombinationLotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
 
Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrived
 
JavaScript!
JavaScript!JavaScript!
JavaScript!
 

JS Essence

  • 7. Goals • JS popularization • JS as engineering tool
  • 9. Roadmap • Embedded JS issues: - bad parts, good parts - imperative skin upon functional nature - misunderstanding of prototype inheritance - missing modules support - performance issues
  • 11. Bad parts • global variables • eval • a++ • math • with • new (Number | String | Boolean) • == vs ===
  • 12. 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)
  • 14. Java(??!)Script • ..one more LISP dialect.. • Mocha • LiveScript • JavaScript
  • 16. Functional nature • functions are the 1-st class objects: - assign to variables - pass as an argument - return as a result
  • 18. OOP in JavaScript • Объект_о-ориентированный • Объектно-ориентированный
  • 20. Classical OOP simulation • Classical OOP inheritance can be simulated: > I would recommend John Resig’s “Class” object http://ejohn.org/blog/simple-javascript-inheritance/
  • 21. Classical OOP simulation Class.extend({ init: function(a, b) { // .ctor this._super(a, b); }, method1: function() { // do something } });
  • 23. Inheritance examples var F = function(n) { this.name = n; } var a = new F(“a”); var b = new F(“b”);
  • 24. 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 // ???
  • 25. 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 // ???
  • 26. Inheritance examples var F = function() {} var a = new F(); a.constructor === F // ???
  • 27. Inheritance examples var F = function() {} F.prototype = , root: “hello world!” -; var a = new F(); a.constructor === F // ???
  • 28. Dynamic inheritance var 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() // ???
  • 31. Modules simulation • No modules. Global variables RULEZZZ!!11
  • 32. Modules simulation • No modules. Global variables RULEZZZ!!11 BAD!
  • 33. Modules simulation • No named modules. BUT functional context (function(global) { . . .})(window)
  • 34. Modules simulation • No named modules. BUT functional context (function(global) { . . .})(window)
  • 35. Modules simulation • No named modules. BUT functional context (function(global) { . . .})(window) var myJQueryVar = $.noConflict()
  • 36. Modules simulation • Namespacing as global variables chains newsite.common.utils newsite.common.services var newsite = newsite || {}; newsite.common = newsite.common || {}; newsite.common.utils = function() , … -;
  • 37. Modules simulation • Namespacing as global variables chains newsite.common.utils newsite.common.services • $LAB .script(“newsite.core.js").wait() .script(“newsite.common.utils.js") .script(“newsite.common.services.js“) .wait(function() { /* ready */ })
  • 38. Modules simulation RequireJS http://requirejs.org/
  • 39. 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>
  • 40. entry_points/main.js require( *“dir/module1“, “dir/module2“+, function(m1, m2) { /* to do: … */ } );
  • 41. dir/module1.js define( *“dependency-on-some-other-modules”+, function () { return { color: "black", clear: function() ,…- }; } );
  • 43. IE6?!
  • 44. Performance - prologue • It’s still possible to write slow JavaScript on the new fast JavaScript engines • JavaScript performance directly affects user experience
  • 46. Performance • Loading & execution • DOM scripting
  • 47. 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)
  • 48. 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
  • 49. 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
  • 50. RequireJS DO all the job!
  • 51. DOM Scripting • Live DOM collections • Repaint and Reflow • Handling DOM events
  • 52. 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
  • 53. Toll bridge • Touch the DOM lightly • Stay within ECMAScript as much as possible
  • 54. HTML collections • Expensive live collections • Use local variables when accessing collection elements
  • 55. Repaints and reflows • DOM tree • Render tree
  • 56. 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
  • 57. Redraw process Once the reflow is complete, the browser redraws the affected parts of the screen
  • 58. 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
  • 59. Queuing and flushing reflows • Browsers optimize reflow by queuing changes and performing them in batches • Never request layout information while it’s being changed
  • 60. Queuing and flushing reflows • offsetX • scrollX • clientX • getComputedStyle (currentStyle in IE) * X – Top, Left, Width, Height
  • 61. Minimizing repaints and reflows • Combine multiple DOM and style changes into a batch and apply them once
  • 62. Batching DOM changes • Take the element off of the document flow • Apply multiply changes • Bring the element back to the document
  • 63. 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
  • 64. Take elements out of the flow for animation 1. Use absolute positioning 2. Animate the element 3. When the animation is done, restore the positioning JQuery DO this job for you!
  • 65. 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
  • 66. Performance essence • http://jsperf.com/ • http://www.developer.nokia.com/Community /Wiki/JavaScript_Performance_Best_Practices
  • 68. How to move next • Primary • Advanced • Meta-level
  • 69. How to move next • http://habrahabr.ru/post/117838/