0
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 pro...
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 ...
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   ...
Classical OOP simulationClass.extend({    init: function(a, b) {          // .ctor          this._super(a, b);    },    me...
Inheritance examples• Some examples
Inheritance examplesvar F = function(n) {  this.name = n;}var a = new F(“a”);var b = new F(“b”);
Inheritance examplesvar F = function(n) {  this.name = n;}F.prototype = , root: “hello world!” -;var a = new F(“a”);var b ...
Inheritance examplesvar F = function(n) {   this.name = n;}F.prototype = , root: “hello world!” -;var a = new F(“a”);var b...
Inheritance examplesvar F = function() {}var a = new F();a.constructor === F // ???
Inheritance examplesvar F = function() {}F.prototype = , root: “hello world!” -;var a = new F();a.constructor === F // ???
Dynamic inheritancevar F = function() {};F.prototype = {    count: 0,    augment: function() {            ++F.prototype.co...
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 myJQueryV...
Modules simulation• Namespacing as global variables chains    newsite.common.utils    newsite.common.services  var newsite...
Modules simulation• Namespacing as global variables chains     newsite.common.utils     newsite.common.services• $LAB     ...
Modules simulation   RequireJS  http://requirejs.org/
Modules simulation - RequireJS<!DOCTYPE html><html>  <head>    <title>My Sample Project</title>    <script         src="pa...
entry_points/main.jsrequire(   *“dir/module1“, “dir/module2“+,   function(m1, m2) { /* to do: … */ });
dir/module1.jsdefine(   *“dependency-on-some-other-modules”+,   function () {       return {             color: "black",  ...
Performance
IE6?!
Performance - prologue• It’s still possible to write slow JavaScript on  the new fast JavaScript engines• JavaScript perfo...
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 <scr...
Loading and execution• Put <script> tags as close to the bottom of the  <body> as possible• Load scripts in groups  (100 k...
Non-blocking loading• <script defer> (IE 4+, FF 3.5+)• Dynamic <script> elements  – Parallel non-blocking loading  – Put i...
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 doc...
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 processWhen a DOM tree change affects elementgeometry – browser recalculate geometry andposition of elements that c...
Redraw processOnce the reflow is complete, the browserredraws the affected parts of the screen
When does a reflow happen?• Page renders initially• Visible DOM elements are added or removed• Elements change position• E...
Queuing and flushing reflows• Browsers optimize reflow by queuing changes  and performing them in batches• Never request l...
Queuing and flushing reflows•   offsetX•   scrollX•   clientX•   getComputedStyle (currentStyle in IE)* X – Top, Left, Wid...
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 doc...
Ways to modify the DOM off the            document• Hide, apply changes and show again• Use document fragment to build sub...
Take elements out of the flow for             animation1. Use absolute positioning2. Animate the element3. When the animat...
Event delegation• A lot of event handlers affects  memory, performance and useless since user  clicks 1 button of 100 for ...
Performance essence• http://jsperf.com/• http://www.developer.nokia.com/Community  /Wiki/JavaScript_Performance_Best_Pract...
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/
Upcoming SlideShare
Loading in...5
×

JS Essence

1,956

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,956
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "JS Essence"

  1. 1. JavaScript
  2. 2. Get acquainted
  3. 3. TargetProcess
  4. 4. TP2 - Rich UI
  5. 5. TP2 - Rich UI
  6. 6. TP3 - high-performance UI
  7. 7. Goals• JS popularization• JS as engineering tool
  8. 8. JS Phenomena
  9. 9. Roadmap• Embedded JS issues: - bad parts, good parts - imperative skin upon functional nature - misunderstanding of prototype inheritance - missing modules support - performance issues
  10. 10. Bad parts, good parts
  11. 11. Bad parts• global variables• eval• a++• math• with• new (Number | String | Boolean)• == vs ===
  12. 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)
  13. 13. Java(??!)Script
  14. 14. Java(??!)Script• ..one more LISP dialect..• Mocha• LiveScript• JavaScript
  15. 15. Programming paradigms
  16. 16. Functional nature• functions are the 1-st class objects: - assign to variables - pass as an argument - return as a result
  17. 17. Inheritance?Why?
  18. 18. OOP in JavaScript• Объект_о-ориентированный• Объектно-ориентированный
  19. 19. Prototype chain
  20. 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. 21. Classical OOP simulationClass.extend({ init: function(a, b) { // .ctor this._super(a, b); }, method1: function() { // do something }});
  22. 22. Inheritance examples• Some examples
  23. 23. Inheritance examplesvar F = function(n) { this.name = n;}var a = new F(“a”);var b = new F(“b”);
  24. 24. Inheritance examplesvar 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. 25. Inheritance examplesvar 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. 26. Inheritance examplesvar F = function() {}var a = new F();a.constructor === F // ???
  27. 27. Inheritance examplesvar F = function() {}F.prototype = , root: “hello world!” -;var a = new F();a.constructor === F // ???
  28. 28. 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() // ???
  29. 29. Functions• apply• call
  30. 30. Modules
  31. 31. Modules simulation• No modules. Global variables RULEZZZ!!11
  32. 32. Modules simulation• No modules. Global variables RULEZZZ!!11 BAD!
  33. 33. Modules simulation• No named modules. BUT functional context (function(global) { . . .})(window)
  34. 34. Modules simulation• No named modules. BUT functional context (function(global) { . . .})(window)
  35. 35. Modules simulation• No named modules. BUT functional context (function(global) { . . .})(window) var myJQueryVar = $.noConflict()
  36. 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. 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. 38. Modules simulation RequireJS http://requirejs.org/
  39. 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. 40. entry_points/main.jsrequire( *“dir/module1“, “dir/module2“+, function(m1, m2) { /* to do: … */ });
  41. 41. dir/module1.jsdefine( *“dependency-on-some-other-modules”+, function () { return { color: "black", clear: function() ,…- }; });
  42. 42. Performance
  43. 43. IE6?!
  44. 44. Performance - prologue• It’s still possible to write slow JavaScript on the new fast JavaScript engines• JavaScript performance directly affects user experience
  45. 45. High Performance JavaScript
  46. 46. Performance• Loading & execution• DOM scripting
  47. 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. 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. 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. 50. RequireJS DO all the job!
  51. 51. DOM Scripting• Live DOM collections• Repaint and Reflow• Handling DOM events
  52. 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. 53. Toll bridge• Touch the DOM lightly• Stay within ECMAScript as much as possible
  54. 54. HTML collections• Expensive live collections• Use local variables when accessing collection elements
  55. 55. Repaints and reflows• DOM tree• Render tree
  56. 56. Reflow processWhen a DOM tree change affects elementgeometry – browser recalculate geometry andposition of elements that could have beenaffected by the change and reconstructs theRender tree
  57. 57. Redraw processOnce the reflow is complete, the browserredraws the affected parts of the screen
  58. 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. 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. 60. Queuing and flushing reflows• offsetX• scrollX• clientX• getComputedStyle (currentStyle in IE)* X – Top, Left, Width, Height
  61. 61. Minimizing repaints and reflows• Combine multiple DOM and style changes into a batch and apply them once
  62. 62. Batching DOM changes• Take the element off of the document flow• Apply multiply changes• Bring the element back to the document
  63. 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. 64. Take elements out of the flow for animation1. Use absolute positioning2. Animate the element3. When the animation is done, restore the positioning JQuery DO this job for you!
  65. 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. 66. Performance essence• http://jsperf.com/• http://www.developer.nokia.com/Community /Wiki/JavaScript_Performance_Best_Practices
  67. 67. Patterns• http://www.addyosmani.com/resources/esse ntialjsdesignpatterns/book/
  68. 68. How to move next• Primary• Advanced• Meta-level
  69. 69. How to move next• http://habrahabr.ru/post/117838/
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×