5 Tips for Better JavaScript

Preview:

DESCRIPTION

Love it or hate it, JavaScript is playing an increasingly important role in the next generation of web and mobile apps. As code continues to move from the server to the client, JavaScript is being used to do more than simple HTML manipulation. Be prepared for this transition and make sure the JavaScript you write is optimized and ready to perform on desktops and devices! In this session, you will learn ten practical tips that you can use today to write faster, more maintainable, memory friendly JavaScript.

Citation preview

5 TipsFor Better

@toddanglin

NEWtal

k

JAVASCRIPT!

<TODO: HAPPY PLACE IMAGE>

JAVASCRIPT.

@toddanglinBrought to you by @KendoUI

Why JavaScript?

WHY?!

It’s the first?

It’s the best?

It’s the easiest?

It’s the fastest?

It’s everywhere.

JavaScript.

I am your father.

No, really.Brendan Eich.Netscape.

“JS had to 'look like Java' only less so, be

Java’s dumb kid brother or boy-

hostage sidekick. Plus, I had to be done in ten

days or something worse than JS would

have happened”

::::

Sept 1995Netscape

Aug 1996Microsoft

June 1997ECMAScript

//

Mar 1999XHR

Feb 2005Ajax

Aug 2001IE6

FirefoxSafari

ChromeMobile

JavaScript won by default.

If you're the last man left on earth, it doesn't matter how

ugly you are when the women come to re-populate the

planet.Scott Koon

Can’t Beat ‘em,Join ‘em.

Modern JavaScriptFaster. Easier. Better.

Attwood’s Law:Any application that can be

written in JavaScript, will eventually be written in

JavaScript2007

MOST COMMON PROBLEMS

1.Slow Execution2.Memory leaks3.Poor Code

Organization4.Lack of Understanding

5(ISH) TIPS

From real masters:JordanIvan

TsvetomirAtanasBurkeJohn

Brandon

TIP #1jQuery is a friend…

…that will stab you in the back.

Prove It

SUB-TIP

1.1CACHE OBJECTS

$("#myDiv").css("color","red");$("#myDiv").css("opacity",1);

BAD

$("#myDiv").css("color","red")

.css("opacity",1);

BETTER

var $myDiv = $("#myDiv");$myDiv.css("color","red");$myDiv.css("opacity",1);

BEST*

Prove It

SUB-TIP

1.2NATIVE LOOPS

$.each(arr, function (i) {i / 2;});BAD

arr.forEach(function (i) {i / 2;});BETTER

var i = 0, len = arr.length;for (i = 0; i < len; i += 1) {

i / 2;}

BEST*

Prove It

TIP #2Avoid Global Variables

They're slow & rude.

function add(num1, num2){ return num1 + num2;}

var result = add(5, 10);16:23

Prove It

var name = "Todd";function sayHello(){

alert(name);}

function sayHello(){ var name = "Todd";

alert(name);}

16:23

BAD

BETTER

Closures & Module Pattern

var app = (function(){ var _name = "Todd";

return{ sayHello: function(){

alert(_name); }

}}());

app.sayHello();

16:23

BEST(ISH)

SUB-TIP

2.1SUPER PATTERN

(function(window,$,c){ var _private = "Todd";

function privateClass(){}

function myWidget(){} myWidget.prototype.doSomething = function(){}

window.myWidget = myWidget;}(window,jQuery,console);

Self-Executing Anonymous Functions + Global Imports + Prototype

Prove It

TIP #3Bind to Events & Pub/Sub

Just listen.

<button id="btn" onclick="sayHello();">Click Me</button>

$(function(){$(“#btn").on("click",sayHello);

});

16:23

BAD

BETTER

$(document).on("click","button",

sayHello);

16:23

BEST

Why?

SUB-TIP

3.1UNBINDING EVENTS

$(document).off("click","button");

$(document).remove("button");

OR

function doSomthing{...doSomethingElse();

doOneMoreThing();}

16:23

BAD

function doSomething{...$.trigger("DO_SOMETHING_DONE");

}

$(document).on("DO_SOMETHING_DONE", function(){

doSomethingElse();});

16:23

BETTER

function doSomething(){var dfd = new $.Deferred();

//Do something async, then...//dfd.resolve();

return dfd.promise();}

function doSomethingElse(){$.when(doSomething()).then(//The

next thing);}

16:23

ALSO BETTER

TIP #4Don't fondle the DOM.

Go with the flow.

My Awesome Page

Copyright Fo'eva

Lorem ipsumy samplish jibber jabbish text only meant to serve as a placeholder, and much like Pi, should never repeat or be read much beyond the first few characters.

function doSomething{...var $list = $("body").append("<ul>");for(var i = 0; i < 10; i++){

$list.append("<li>"+ i +"</li>") }}

16:23

BAD

function doSomething{...var $domChunk = $("<ul>");for(var i = 0; i < 10; i += 1){

$domChunk.append("<li>"+ i +"</li>"); }

$("body").append($domChunk);}

16:23

BETTER

SUB-TIP

4.1DOM SPEED WITH

STRINGS & INNERHTMLfunction doSomething{

...var domString = "<ul>";for(var i = 0; i < 10; i += 1){

domString += "<li>"+ i +"</li>"; }

domString += "</ul>"$("body")[0].innerHTML = domString;

} Prove It

<script type="text/x-kendo-template" id="tmp">

<ul> #for(var i = 0; i < data.length; i

+= 1){# <li>#= data[i] #</li>

#}#</ul>

</script>

function doSomething(){var myData = [1,..,10];var template = kendo.template($

("#tmp").html());$("body").append(template(myData));

}16:23

BEST

Prove It

TIP #5Learn a module pattern.

And use it.

PERFORMANCE CONVENIENCE

A.js

B.js

Manual (index.html)<script src="B.js"></script><script src="A.js"></script><script src="main.js"></script>

Module Loader (main.js)require(["A","B"], function(){

//Dependencies are loaded});

USE JSLINTGuaranteed to Hurt Your Feelings™

16:23

BONUS

TIPS

MINIFY YOUR JSWords are for humans.

MASTER BROWSER DEV TOOLS

Debug JavaScript where it runs.

Debugging

console.log()

Fix IE<script type="text/javascript">

<!--Console global variable fix for IE-->

if (!this.console) { window.console = {

log: function() {} };}

</script>

16:23

Resources for Study• Books– JavaScript: The Good Parts (Crockford)– JavaScript: The Definitive Guide

(Flanagan)– JavaScript Patterns (Stefanov)– High Performance JavaScript (Zakas)

16:23

console.clear();

JAVASCRIPT, mon.

A&Q

anglin@telerik.com | @toddanglinwww.KendoUI.com