5 Tips for Better JavaScript

download 5 Tips for Better JavaScript

of 57

  • date post

  • Category


  • view

  • download


Embed Size (px)


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.

Transcript of 5 Tips for Better JavaScript

  • 5 TipsFor Better @toddanglin

@toddanglin Brought to you by @KendoUI WhyJavaScript?WHY?! Its the first? Its the best? Its the easiest? Its the fastest? Its everywhere. No, really.Brendan Eich.Netscape. JS had to look like Javaonly less so, be Javasdumb kid brother or boy- hostage sidekick. Plus, I had to be done in tendays or something worsethan JS would havehappened :::: Aug 1996 Microsoft Mar 1999FirefoxXHR Safari Chrome Mobile //Sept 1995NetscapeAug 2001IE6June 1997 ECMAScriptFeb 2005Ajax JavaScript won by default. If youre the last man left on earth, it doesnt matter how uglyyou are when the women come to re-populate the planet. Scott Koon Cant Beat em,Join em. Modern JavaScriptFaster. Easier. Better. Attwoods 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 realmasters:Jordan IvanTsvetomir AtanasBurke John Brandon TIP #1jQuery is a friend that will stab you in the back.Prove It CACHE OBJECTS BAD$("#myDiv").css("color","red");$("#myDiv").css("opacity",1);BETTER$("#myDiv").css("color","red") .css("opacity",1);BEST*var $myDiv = $("#myDiv");$myDiv.css("color","red");$myDiv.css("opacity",1);Prove It NATIVE LOOPSBAD$.each(arr, function (i) {i / 2;});BETTERarr.forEach(function (i) {i / 2;});BEST*var i = 0, len = arr.length;for (i = 0; i < len; i += 1) { i / 2;}Prove It TIP #2Avoid Global Variables Theyre slow & rude. function add(num1, num2){return num1 + num2;}var result = add(5, 10);Prove It16:39 BADvar name = "Todd";function sayHello(){ alert(name);}BETTERfunction sayHello(){ var name = "Todd"; alert(name);}16:39 Closures & Module Pattern BEST(ISH)var app = (function(){ var _name = "Todd";return{ sayHello: function(){ alert(_name);}}}());app.sayHello();16:39 SUPER PATTERN Self-Executing Anonymous Functions + Global Imports + Prototype(function(window,$,c){ var _private = "Todd"; function privateClass(){} function myWidget(){} myWidget.prototype.doSomething =function(){} window.myWidget = myWidget;}(window,jQuery,console);Prove It TIP #3Bind to Events & Pub/SubJust listen. BADClick Me BETTER$(function(){ $(#btn").on("click",sayHello);});16:39 BEST$(document).on("click", "button", sayHello);Why?16:39 UNBINDING EVENTS$(document).off("click","button"); OR$(document).remove("button"); BADfunction doSomthing{ ... doSomethingElse();doOneMoreThing();}16:39 BETTERfunction doSomething{ ... $.trigger("DO_SOMETHING_DONE");}$(document).on("DO_SOMETHING_DONE", function(){doSomethingElse(); });16:39 ALSO BETTERfunction doSomething(){ var dfd = new $.Deferred();//Do something async, then...//dfd.resolve();return dfd.promise();}function doSomethingElse(){ $.when(doSomething()).then(//The nextthing);}16:39 TIP #4Dont fondle the DOM. Go with the flow. My Awesome Page 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.Copyright Foeva BAD function doSomething{...var $list = $("body").append("

  • ");for(var i = 0; i < 10; i++){ $list.append("
  • "+ i +"")} }16:39 BETTER function doSomething{...var $domChunk = $("
    • ");for(var i = 0; i < 10; i += 1){ $domChunk.append("
    • "+ i +"");}$("body").append($domChunk); }16:39 DOM SPEED WITH STRINGS & INNERHTMLfunction doSomething{ ... var domString = "
      • "; for(var i = 0; i < 10; i += 1){domString += "
      • "+ i +""; } domString += "
      " $("body")[0].innerHTML = domString;}Prove It BEST
    function doSomething(){var myData = [1,..,10];var template = kendo.template($("#tmp").html());$("body").append(template(myData)); }16:39Prove It TIP #5Learn a module pattern.And use it. PERFORMANCE CONVENIENCE Manual (index.html)A.js Module Loader (main.js)B.js require(["A","B"], function(){ //Dependencies are loaded }); USE JSLINTGuaranteed to Hurt Your Feelings MINIFY YOUR JS Words are for humans.MASTER BROWSER DEV TOOLS Debug JavaScript where it runs.16:39 Debugging console.log() Fix IE 16:39 Resources for Study Books JavaScript: The Good Parts (Crockford) JavaScript: The Definitive Guide (Flanagan) JavaScript Patterns (Stefanov) High Performance JavaScript (Zakas)16:39 console.clear(); A&Qanglin@telerik.com | @toddanglin www.KendoUI.com