• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Javascript Everywhere
 

Javascript Everywhere

on

  • 4,752 views

Presentation to the MIT IAP HTML5 Game Development Class on Debugging and Optimizing Javascript, Local storage, Offline Storage and Server side Javascript with Node.js

Presentation to the MIT IAP HTML5 Game Development Class on Debugging and Optimizing Javascript, Local storage, Offline Storage and Server side Javascript with Node.js

Statistics

Views

Total Views
4,752
Views on SlideShare
3,573
Embed Views
1,179

Actions

Likes
1
Downloads
51
Comments
0

7 Embeds 1,179

http://cykod.com 1169
http://localhost 3
http://webcache.googleusercontent.com 3
http://twitter.com 1
http://admin.totalmarketing.com 1
http://test.cykod.com 1
http://translate.googleusercontent.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

Javascript Everywhere Javascript Everywhere Presentation Transcript

  • Javascript Everywhere Online, Offline and on the Server Pascal Rettig http://www.cykod.com @cykod
  • Topics• Debugging Javascript• Optimizing Javascript• Local Storage• Offline Storage• Server side Javascript + Web Sockets (Time permitting)
  • Debugging Javascript Or, alert(“Can only take you so far”);
  • Firebughttp://getfirebug.com/
  • Other browsers• Chrome and IE8 have similar tools to Firebug built in.• Tools -> Developer Tools in both
  • Firebug 101• Inspecting• Modifying• Tracking resources
  • Firebug 102Getting rid of alert(...)• Firebug console• console.log(...), console.warn(...), console.error(...)• execute javascript directly from the console• Firebug needs to be open
  • Javascript Debugging• Firebug step debugger• Setting watches• Setting breakpoints• Setting conditional breakpoints
  • The best type of bug...
  • The best type of bug...... is one that’s caught for you.
  • Javascript is a lax languageYour javascript code will only be as rigorous as you are.
  • Consider lint’ing http://javascriptlint.com/ Command line tool by Matthias Miller built on thework done by Douglas Crockford (“JS, the good parts”)
  • Automated Testing Frameworks QUnit - used in JQueryJasmine - Created by Pivotal Labs, Inspired by RSpec
  • QUnit By John Resig, Founder of JQuery http://docs.jquery.com/Qunittest("a basic test example", function() { ok( true, "this test is fine" ); var value = "hello"; equals( "hello", value, "We expect value to be hello" );});module("Module A");test("first test within module", function() { ok( true, "all pass" );});
  • Jasmine From Pivotal Labs, Successor to JsUnit, inspired (partly) by RSpec http://pivotal.github.com/jasmine/describe(Calculator, function () { var counter = 0 it(can add a number, function () { counter = counter + 2; // counter was 0 before expect(bar).toEqual(2); }); it(can multiply a number, function () { counter = counter * 5; // counter was 2 before expect(bar).toEqual(10); });});
  • Optimizing ProfilingJavascript OptimizationNetwork Optimization
  • We should forget about smallefficiencies, say about 97% of the time:premature optimization is the root ofall evil. - Donald Knuth
  • Javascript Profiling with Firebug
  • Javascript Profiling with Firebug• Click “profile”
  • Javascript Profiling with Firebug• Click “profile”• Wait
  • Javascript Profiling with Firebug• Click “profile”• Wait• Click “profile” again
  • Some questions...• Best way to add elements to arrays?• Best way to create lots of objects?• How bad is concatenating onto a HTML string?• How much to globals hurt?
  • Arrays http://jsperf.com/array-selection-methods/2var arr = [] var arr = []for (var i = 0; i < len; i++) { for (var i = 0; i < len; i++) { arr.push(i)  arr[arr.length] = i} }var arr = new Array(len) var arr = []for (var i = 0; i < len; i++) { for (var i = 0; i < len; i++) { arr[i] = i  arr[i] = i} } var arr = []var arr = [] for (i = 0; i < len; ifor (i = 0; i < len; i++) { ++) { arr.push(i)  arr[i] = i} }
  • Object Creation http://jsperf.com/object-initialization-patterns-testvar Obj1 = function() {} var Obj3 = function() { Obj1.prototype.yay = function(x) {};   function yay(x) {}; Obj1.prototype.boo = function(y) {};   function boo(y) {};   return {for (var i = 0; i < numObjects; i++) {    yay: yay, new Obj1();    boo: boo}   } } var Obj2 = function() {  this.yay = function(x) {}; for (var i = 0; i < numObjects; i++) {  this.boo = function(y) {};  new Obj3(); } }for (var i = 0; i < numObjects; i++) { new Obj2();}
  • Double check your intuition...• http://jsperf.com• http://jsfiddle.net/
  • Web PagePerformance Tuning
  • Speed up game launch• Games are often asset loading bound• Consider a CDN (S3/Cloudfront)• 24bit vs 8bit files• Sprite maps• Async or Load on demand Javascript: • http://requirejs.org/ • http://headjs.com
  • Taking Javascript Home• Local Storage• Offline storage
  • Local StorageStore data on the client for later use.
  • Isn’t that just like a cookie?
  • Isn’t that just like a cookie? Yes and no
  • Local Storage vs. Cookies Sent Available Size Number Each on Limit Limit Request? Server? Local 5-10MB N/A No NoStorageCookies 4K 20 Yes Yes
  • Local Storage works for:• Firefox 3.5, Safari 4, IE8, Chrome 4+• Saving game state between visits without a server• Storing larger pieces of data
  • Testing for Local StorageTesting directly (From Dive Into HTML5)function supports_local_storage() { try { return localStorage in window && window[localStorage] !== null; } catch(e){ return false; }}Using Modernizrif (Modernizr.localstorage) { // Local Storage available}
  • Using Local Storage// Add an item to local storagetry { localStorage.setItem(identifierString, valueString); localStorage.identifierString = valueString;} catch(e) { if (e == QUOTA_EXCEEDED_ERR) { /* Do something */ }}// Retrieve an itemlocalStorage.getItem(identifierString);localStorage.identifierString;// Remove an itemlocalStorage.removeItem(identifierString);delete localStorage[identifierString];// Clear the entire per-domain DBlocalStorage.clear();
  • Strings only... Probably want to create an API on top of localStorageStorage.prototype.setObject = function(key, value) { this.setItem(key, JSON.stringify(value));} Storage.prototype.getObject = function(key) { return JSON.parse(this.getItem(key));}http://hacks.mozilla.org/2009/06/localstorage/
  • Better yet, use a library... http://www.jstorage.info/$.jStorage.set(key, value)value = $.jStorage.get(key)value = $.jStorage.get(key, "default value")Requires a library like jQuery, Prototype Backwards compatible with IE7
  • Other HTML5 Storage Options• sessionStorage - same as localStorage but per tab• Web SQL - Provides SQLite compatible DB storage - WebKit only - good for mobile sync
  • Offline Storage
  • Why?• Make apps available offline (Duh!)• Make mobile apps that sync when networked• Force browsers to keep assets available
  • The set-up1. Add a manifest file to your HTML: <html manifest="/cache.manifest">2. Make sure your manifest is served with: AddType text/cache-manifest .manifest3. Create the manifest listing cached files: CACHE MANIFEST /style.css /application.js /images/image1.jpg ... /images/imageN.jpg4. Listen for events on window.applicationCache
  • The Events on window.applicationCache Event When checking First event, checking for a manifest noupdate Manifest hasn’t changeddownloading Downloading the update progress Periodically while downloading Everything downloading, application cached cached A new cached is available, useupdateready swapCache() to swap out Something returned a 404, so cache obsolete is being deleted error Something, somewhere went wrong
  • But...If you have a simple app that you just want tobe cacheable online, you don’t need to doanything special
  • Gotcha’s• Disable server caching while testing or your will go insane• Make sure to update your manifest file each time you update a resource. e.g. “revisionXX”• Probably want to auto-generate your manifest file from a script so you aren’t missing files.
  • Javascript on the Server
  • Why?• Leverage existing javascript codebase• Async good support for realtime and Websockets
  • Introducing Node.js http://nodejs.org/• Built on Embedded Google V8 Engine• Check out nodejs.com for installation• Single threaded async• Lots of callbacks
  • Node Packages• NPM - node package manager, sort of like Rubygems for node• As easy as “npm install socket.io”• export NODE_PATH=/path/to/node/lib to use in node
  • Simplest Examplevar http = require(http);http.createServer(function (req, res) { res.writeHead(200, {Content-Type: text/plain}); res.end(Hello Worldn); }).listen(8124, "127.0.0.1");console.log(Server running at http://127.0.0.1:8124/);
  • WebSockets: the problem• Want realtime messaging• Not supported in older browsers• Removed from FF4 for the time being
  • WebSockets: a solution http://socket.io/•Supports native WebSockets•Has a fallback for flash•Handles it all for you
  • The Servervar http = require(http), io = require(socket.io), fs = require (fs),server = http.createServer(function(req, res){ fs.readFile("client/index.html", "binary", function(err, file) { res.writeHead(200, {Content-Type: text/html}); res.end(file); });});server.listen(8080);var socket = io.listen(server);socket.on(connection, function(client){ var messages = 0; console.log(New Client); client.on(message, function(message){ console.log(message); setTimeout(function() { client.send("Pong" + messages++); },500); }); client.on(disconnect, function(){ console.log(Client disconnected); });});
  • The Client<script src="http://127.0.0.1:8080/socket.io/socket.io.js"></script>...<body><div id=status></div><script> var socket = new io.Socket("127.0.0.1"); socket.on(connect, function(){ $(#status).html(Connected!); socket.send("Ping"); }); socket.on(message, function(req){ $(#status).html("Received: " + req); setTimeout(function() { socket.send("Ping"); },500); }); socket.on(disconnect, function(){ $("#status").html("Disconnected"); }); socket.connect();</script>
  • Thanks! Pascal Rettigpascal@cykod.com