101
JavaScript make the right choices

JavaScript - Make the right choices

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: JavaScript - Make the right choices

JavaScriptmake the right choices

Page 2: JavaScript - Make the right choices

Damian Wielgosik

Page 3: JavaScript - Make the right choices

about me ;-)

Page 4: JavaScript - Make the right choices

ferrante.plvarjs.com

http://twitter.com/varjs

Page 5: JavaScript - Make the right choices

1. Begin with ECMAScript

Page 6: JavaScript - Make the right choices

ECMAScript

Page 7: JavaScript - Make the right choices

sometimes it’s difficult...

Page 8: JavaScript - Make the right choices

... to speak in a human language

Page 9: JavaScript - Make the right choices

... znaleźć ludzki językDmitry Soshnikov

your personal ECMAScript teacher

Page 10: JavaScript - Make the right choices

Participate in the future!

Page 11: JavaScript - Make the right choices

Harmony - the next ECMAScript standard

Page 12: JavaScript - Make the right choices

mail-archive.com/[email protected]/info.html

they need your feedback!

Page 14: JavaScript - Make the right choices

mail-archive.com/[email protected]/info.html

where is your name?

Page 15: JavaScript - Make the right choices

2. Know your tools

Page 16: JavaScript - Make the right choices

Yes, we all know Firebug and Web Inspector

Page 17: JavaScript - Make the right choices

Hurt your feelings with jslint.com

Page 18: JavaScript - Make the right choices

Yes, we all know Firebug and Web Inspector

Aardwolf - mobile debugging made easy

Page 19: JavaScript - Make the right choices

Memory stats?

Page 20: JavaScript - Make the right choices

Memory?

WebKit Inspector

Page 21: JavaScript - Make the right choices

Memory leaks?

Page 22: JavaScript - Make the right choices

Memory leak checker

Page 23: JavaScript - Make the right choices

Performance?

sIEeve

home.orange.nl/jsrosman/

Page 24: JavaScript - Make the right choices

Memory leaks?

people.mozilla.com/~dbaron/leak-screencasts/

Page 25: JavaScript - Make the right choices

Performance?

Page 26: JavaScript - Make the right choices

var start = +new Date();for (var i = 0; i < 100000; i++);console.log("Result is: ", +new Date() - start);

Page 27: JavaScript - Make the right choices

Better?

Page 28: JavaScript - Make the right choices

console.time("My test"); for (var i = 0; i < 100000; i++); console.timeEnd("My test");

Page 29: JavaScript - Make the right choices

Still better?

Page 30: JavaScript - Make the right choices

console.profile("My test"); runApp();console.profileEnd("My test");

Page 31: JavaScript - Make the right choices

The best?

Page 32: JavaScript - Make the right choices

jsperf.com

jsperf.com

Page 33: JavaScript - Make the right choices

jsperf measures operations per second!

Page 34: JavaScript - Make the right choices

Get rid of jQuery if it’s not neccessary - there is http://microjs.com

Page 35: JavaScript - Make the right choices

Hunt on new stuff!

Page 36: JavaScript - Make the right choices

http://js.gd might be a good start!

Page 37: JavaScript - Make the right choices

3. Tips and tricks

Page 38: JavaScript - Make the right choices

it has to be said...

Page 39: JavaScript - Make the right choices

do not optimize prematurely!

Page 40: JavaScript - Make the right choices

do not optimize prematurely!

flickr.com/photos/paulmartincampbell/3583176306/sizes/o/in/photostream/

JavaScript !== Java

Page 41: JavaScript - Make the right choices

var obj = {}; // not new Object()var arr = []; // not new Array();

Page 42: JavaScript - Make the right choices

forget about your old habits!

Page 43: JavaScript - Make the right choices

do not port bad solutions to JavaScript!(aka I don’t need yet another class system in JS)

Page 44: JavaScript - Make the right choices

otherwise they’re gonna find you! ;-)

http://www.fotofaza.pl/podglad_zdjecia,15,ludzie,chuligani.html

Page 45: JavaScript - Make the right choices

4. Real tips and tricks

Page 46: JavaScript - Make the right choices

function calls cost time!

Page 47: JavaScript - Make the right choices

use JS asynchronously when needed

Page 48: JavaScript - Make the right choices

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]();}

Page 49: JavaScript - Make the right choices

oops?

Page 50: JavaScript - Make the right choices
Page 51: JavaScript - Make the right choices

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);}

Page 52: JavaScript - Make the right choices

more interesting results

Page 53: JavaScript - Make the right choices

var fn = function() { console.log("a"); fn();};fn();

Page 54: JavaScript - Make the right choices

stack overflow?

Page 55: JavaScript - Make the right choices

let’s write own scheduler

Page 56: JavaScript - Make the right choices

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 function every 500msscheduler.add(function() { console.log("B"); }, 1000); // like above with 1000ms delayscheduler.run();

Page 57: JavaScript - Make the right choices

one loop to handle similar events

Page 58: JavaScript - Make the right choices

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();

Page 59: JavaScript - Make the right choices

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();

we don’t want to end up with big array indexes - we use the object instead of array

we have never added events for this delay so let’s make an array to store them

let’s store a single event by that

Page 60: JavaScript - Make the right choices

yep, you have to implement stop() method

Page 61: JavaScript - Make the right choices

Timers can be useful with AJAX requests

Page 62: JavaScript - Make the right choices

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/

Page 63: JavaScript - Make the right choices

parseInt(„09”) === 0

Page 64: JavaScript - Make the right choices

JS thinks „09” is an octal number because it starts with 0

Page 65: JavaScript - Make the right choices

parseInt(„09”, 10) === 9

Page 66: JavaScript - Make the right choices

However,parseFloat(„09”) === 9

Page 67: JavaScript - Make the right choices

However,parseFloat(„09”) === 9

Page 68: JavaScript - Make the right choices

document.querySelectorAll("div")returns a NodeList

not an array

Page 69: JavaScript - Make the right choices

var nodes = document.querySelectorAll("div");nodes = [].slice.apply(nodes);

Page 70: JavaScript - Make the right choices

However:„Whether the slice function can be applied successfully to a host object is

implementation-dependent.” - ECMAScript

Page 71: JavaScript - Make the right choices

Speaking of which, how to check if it’s an array?

Page 72: JavaScript - Make the right choices

var arr = [];arr instanceof Array;

Page 73: JavaScript - Make the right choices

Really?

Page 74: JavaScript - Make the right choices

var Array = function() {};var arr = [];arr instanceof Array; // FALSE!

Page 75: JavaScript - Make the right choices

Next?

Page 76: JavaScript - Make the right choices

var arr = [];if ("length" in arr) { // we deal with an array}

Page 77: JavaScript - Make the right choices

Really?

Page 78: JavaScript - Make the right choices

var arr = { "length": 2 };if ("length" in arr) { // we deal with an array... wait a moment!}

Page 79: JavaScript - Make the right choices

Next?

Page 80: JavaScript - Make the right choices

var arr = [];if (Object.prototype.toString.call(arr) === "[object Array]") { // Houston, we have an array}

Page 81: JavaScript - Make the right choices

Ok, but well, you can still modify a toString fn...

Page 82: JavaScript - Make the right choices

Object.prototype.toString = function() { return "";};

Page 83: JavaScript - Make the right choices

Here we go... ECMAScript 5!

Page 84: JavaScript - Make the right choices

var arr = [];if (Array.isArray(arr)) { // w00t!}

Page 85: JavaScript - Make the right choices

Hey, I can still replace it with my own stuff!

Page 86: JavaScript - Make the right choices

Array.isArray = function() { return false;}

Page 87: JavaScript - Make the right choices

Cache the most important functions at the very beginning!

Page 88: JavaScript - Make the right choices

(function() { var isArray = Array.isArray;})();

Page 89: JavaScript - Make the right choices

Or.. if you can, use ECMAScript 5 again

Page 90: JavaScript - Make the right choices

Object.defineProperty(Array, "isArray", { writable: false, configurable: false, enumerable: false, value: Array.isArray}); // thx to @marcoos

Page 91: JavaScript - Make the right choices

Hey, what is that ECMAScript 5 actually?

Page 92: JavaScript - Make the right choices

Hey, what is that ECMAScript actually?

Page 93: JavaScript - Make the right choices

Hey, we’re on mobile, do you have something for us?

Page 94: JavaScript - Make the right choices

yes, I can! Oh, I do.

Page 95: JavaScript - Make the right choices

Use window.scrollTo(0, 1) to get rid of the browser address bar on iOS!

Page 96: JavaScript - Make the right choices

/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/

Page 97: JavaScript - Make the right choices

More?

Page 98: JavaScript - Make the right choices

Visit JSNews on Facebook for more awesomenesshttp://tinyurl.com/jsnewspl

Page 99: JavaScript - Make the right choices

or attend Front-Trends 2012 conferencehttp://front-trends.com

http://lanyrd.com/2012/ft2012/

Page 100: JavaScript - Make the right choices

but first of all, be smart and listen to smart people - there is a lot on the web

Page 101: JavaScript - Make the right choices

Thanks!Slides at:

http://varjs.com/make-right-choices