JavaScript - Make the right choices

8,844 views

Published on

Published in: Technology, Design

JavaScript - Make the right choices

  1. 1. JavaScriptmake the right choices
  2. 2. Damian Wielgosik
  3. 3. about me ;-)
  4. 4. ferrante.pl varjs.comhttp://twitter.com/varjs
  5. 5. 1. Begin with ECMAScript
  6. 6. ECMAScript
  7. 7. sometimes it’s difficult...
  8. 8. ... to speak in a human language
  9. 9. ... znaleźć ludzki język Dmitry Soshnikovyour personal ECMAScript teacher
  10. 10. Participate in the future!
  11. 11. Harmony -the next ECMAScript standard
  12. 12. they need your feedback! mail-archive.com/es-discuss@mozilla.org/info.html
  13. 13. mail-archive.com/es-discuss@mozilla.org/info.html
  14. 14. where is your name? mail-archive.com/es-discuss@mozilla.org/info.html
  15. 15. 2. Know your tools
  16. 16. Yes, we all know Firebug and Web Inspector
  17. 17. Hurt your feelings with jslint.com
  18. 18. Aardwolf - mobile debugging made easyYes, we all know Firebug and Web Inspector
  19. 19. Memory stats?
  20. 20. WebKit InspectorMemory?
  21. 21. Memory leaks?
  22. 22. Memory leak checker
  23. 23. sIEeve Performance?home.orange.nl/jsrosman/
  24. 24. Memory leaks?people.mozilla.com/~dbaron/leak-screencasts/
  25. 25. Performance?
  26. 26. var start = +new Date();for (var i = 0; i < 100000; i++);console.log("Result is: ", +new Date() - start);
  27. 27. Better?
  28. 28. console.time("My test");for (var i = 0; i < 100000; i++);console.timeEnd("My test");
  29. 29. Still better?
  30. 30. console.profile("My test");runApp();console.profileEnd("My test");
  31. 31. The best?
  32. 32. jsperf.com jsperf.com
  33. 33. jsperf measures operations per second!
  34. 34. Get rid of jQuery if it’s not neccessary - there is http://microjs.com
  35. 35. Hunt on new stuff!
  36. 36. http://js.gd might be a good start!
  37. 37. 3. Tips and tricks
  38. 38. it has to be said...
  39. 39. do not optimize prematurely!
  40. 40. JavaScript !== Java do not optimize prematurely!flickr.com/photos/paulmartincampbell/3583176306/sizes/o/in/photostream/
  41. 41. var obj = {}; // not new Object()var arr = []; // not new Array();
  42. 42. forget about your old habits!
  43. 43. do not port bad solutions to JavaScript!(aka I don’t need yet another class system in JS)
  44. 44. otherwise they’re gonna find you! ;-)http://www.fotofaza.pl/podglad_zdjecia,15,ludzie,chuligani.html
  45. 45. 4. Real tips and tricks
  46. 46. function calls cost time!
  47. 47. use JS asynchronously when needed
  48. 48. var arr = [ function() { console.log("A"); }, function() { throw new Error("boom!"); }, function() { console.log("B"); }, function() { console.log("C"); } ];for (var i = 0, ilen = arr.length; i < ilen; i++) { arr[i]();}
  49. 49. oops?
  50. 50. var arr = [ function() { console.log("A"); }, function() { throw new Error("boom!"); }, function() { console.log("B"); }, function() { console.log("C"); } ];for (var i = 0, ilen = arr.length; i < ilen; i++) { window.setTimeout(arr[i], 0);}
  51. 51. more interesting results
  52. 52. var fn = function() { console.log("a"); fn();};fn();
  53. 53. stack overflow?
  54. 54. let’s write own scheduler
  55. 55. var scheduler;(function() { var events = []; scheduler = { add : function(fn, delay) { for (var i = 0, ilen = events.length; i < ilen; i++) { if (events[i].fn === fn) { throw new Error("The event exists in the main event loop"); } } events.push({ fn : fn, delay: delay }); }, run: function() { for (var i = 0, ilen = events.length; i < ilen; i++) { (function(callback, delay) { var fn = function() { callback(); window.setTimeout(fn, delay); }; window.setTimeout(fn, delay); })(events[i].fn, events[i].delay); } } };})();scheduler.add(function() { console.log("A"); }, 500); // it will call a functionevery 500msscheduler.add(function() { console.log("B"); }, 1000); // like above with 1000msdelayscheduler.run();
  56. 56. one loop to handle similar events
  57. 57. var eventLoop;(function() { var events = {}; eventLoop = { add : function(fn, delay) { if (!(delay in events)) { events[delay] = []; } else { for (var i = 0, ilen = events[delay].length; i < ilen; i++) { if (events[delay][i].fn === fn) { throw new Error("The event exists in the main event loop"); } } } events[delay].push(fn); }, run: function() { for (var delay in events) { (function(stack, delay) { var fn = function() { for (var i = 0, ilen = stack.length; i < ilen; i++) { stack[i](); } window.setTimeout(fn, delay); }; window.setTimeout(fn, delay); })(events[delay], delay); } } };})();eventLoop.add(function() { console.log("A"); }, 500);eventLoop.add(function() { console.log("B"); }, 500);eventLoop.run();
  58. 58. var eventLoop;(function() { we don’t want to end up with big array indexes - var events = {}; we use the object instead of array eventLoop = { add : function(fn, delay) { if (!(delay in events)) { we have never added events for this delay so let’s events[delay] = []; make an array to store them } else { for (var i = 0, ilen = events[delay].length; i < ilen; i++) { if (events[delay][i].fn === fn) { throw new Error("The event exists in the main event loop"); } } } events[delay].push(fn); let’s store a single event by that }, run: function() { for (var delay in events) { (function(stack, delay) { var fn = function() { for (var i = 0, ilen = stack.length; i < ilen; i++) { stack[i](); } window.setTimeout(fn, delay); }; window.setTimeout(fn, delay); })(events[delay], delay); } } };})();eventLoop.add(function() { console.log("A"); }, 500);eventLoop.add(function() { console.log("B"); }, 500);eventLoop.run();
  59. 59. yep, you have to implement stop() method
  60. 60. Timers can be useful with AJAX requests
  61. 61. var throttle = function(fn, delay) { var timer = null; return function () { var context = this; var args = arguments; clearTimeout(timer); timer = setTimeout(function () { fn.apply(context, args); }, delay); }; }; $(input.username).keypress(throttle(function (event) { // do the Ajax request }, 250));http://remysharp.com/2010/07/21/throttling-function-calls/
  62. 62. parseInt(„09”) === 0
  63. 63. JS thinks „09” is an octal number because it starts with 0
  64. 64. parseInt(„09”, 10) === 9
  65. 65. However,parseFloat(„09”) === 9
  66. 66. However,parseFloat(„09”) === 9
  67. 67. document.querySelectorAll("div") returns a NodeList not an array
  68. 68. var nodes = document.querySelectorAll("div");nodes = [].slice.apply(nodes);
  69. 69. However:„Whether the slice function can be applied successfully to a host object is implementation-dependent.” - ECMAScript
  70. 70. Speaking of which,how to check if it’s an array?
  71. 71. var arr = [];arr instanceof Array;
  72. 72. Really?
  73. 73. var Array = function() {};var arr = [];arr instanceof Array; // FALSE!
  74. 74. Next?
  75. 75. var arr = [];if ("length" in arr) { // we deal with an array}
  76. 76. Really?
  77. 77. var arr = { "length": 2 };if ("length" in arr) { // we deal with an array... wait a moment!}
  78. 78. Next?
  79. 79. var arr = [];if (Object.prototype.toString.call(arr) === "[object Array]") { // Houston, we have an array}
  80. 80. Ok, but well, you can still modify a toString fn...
  81. 81. Object.prototype.toString = function() { return "";};
  82. 82. Here we go... ECMAScript 5!
  83. 83. var arr = [];if (Array.isArray(arr)) { // w00t!}
  84. 84. Hey, I can still replace it with my own stuff!
  85. 85. Array.isArray = function() { return false;}
  86. 86. Cache the most important functions at the very beginning!
  87. 87. (function() { var isArray = Array.isArray;})();
  88. 88. Or.. if you can, use ECMAScript 5 again
  89. 89. Object.defineProperty(Array, "isArray", { writable: false, configurable: false, enumerable: false, value: Array.isArray}); // thx to @marcoos
  90. 90. Hey, what is that ECMAScript 5 actually?
  91. 91. Hey, what is that ECMAScript actually?
  92. 92. Hey, we’re on mobile, do you have something for us?
  93. 93. yes, I can! Oh, I do.
  94. 94. Use window.scrollTo(0, 1) to get rid of the browser address bar on iOS!
  95. 95. /mobile/i.test(navigator.userAgent) && !location.hash && setTimeout (function () { if (!pageYOffset) window.scrollTo(0, 1); }, 1000); thanks to amazing work by Remy Sharphttp://remysharp.com/2010/08/05/doing-it-right-skipping- the-iphone-url-bar/
  96. 96. More?
  97. 97. Visit JSNews on Facebook for more awesomeness http://tinyurl.com/jsnewspl
  98. 98. or attend Front-Trends 2012 conference http://front-trends.com http://lanyrd.com/2012/ft2012/
  99. 99. but first of all, be smart and listen to smart people - there is a lot on the web
  100. 100. Thanks! Slides at:http://varjs.com/make-right-choices

×