SlideShare uma empresa Scribd logo
1 de 54
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”);
Firebug
http://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 102
Getting 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 language
Your javascript code will only be as rigorous as you are.
Consider lint’ing
               http://javascriptlint.com/

  Command line tool by Matthias Miller built on the
work done by Douglas Crockford (“JS, the good parts”)
Automated Testing
      Frameworks
              QUnit - used in JQuery
Jasmine - Created by Pivotal Labs, Inspired by RSpec
QUnit
          By John Resig, Founder of JQuery
             http://docs.jquery.com/Qunit

test("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
        Profiling
Javascript Optimization
Network Optimization
We should forget about small
efficiencies, say about 97% of the time:
premature optimization is the root of
all 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/2
var 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; i
for (i = 0; i < len; i++) {
                                   ++) {
 arr.push(i)
                                    arr[i] = i
}
                                   }
Object Creation
  http://jsperf.com/object-initialization-patterns-test
var 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 Page
Performance 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 Storage
Store 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         No
Storage


Cookies     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
             Storage
Testing directly (From Dive Into HTML5)
function supports_local_storage() {
   try {
      return 'localStorage' in window &&
              window['localStorage'] !== null;
   } catch(e){ return false; }
}

Using Modernizr
if (Modernizr.localstorage) {
   // Local Storage available
}
Using Local Storage
// Add an item to local storage
try {
  localStorage.setItem(identifierString, valueString);
  localStorage.identifierString = valueString;
} catch(e) {
  if (e == QUOTA_EXCEEDED_ERR) { /* Do something */ }
}

// Retrieve an item
localStorage.getItem(identifierString);
localStorage.identifierString;

// Remove an item
localStorage.removeItem(identifierString);
delete localStorage[identifierString];

// Clear the entire per-domain DB
localStorage.clear();
Strings only...
     Probably want to create an API on top
                of localStorage

Storage.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-up
1. Add a manifest file to your HTML:
   <html manifest="/cache.manifest">

2. Make sure your manifest is served with:
   AddType text/cache-manifest .manifest

3. Create the manifest listing cached files:
   CACHE MANIFEST
   /style.css
   /application.js
   /images/image1.jpg
   ...
   /images/imageN.jpg

4. Listen for events on window.applicationCache
The Events on
  window.applicationCache

   Event      When

  checking    First event, checking for a manifest

 noupdate     Manifest hasn’t changed

downloading   Downloading the update

  progress    Periodically while downloading
              Everything downloading, application
  cached      cached
              A new cached is available, use
updateready   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 to
be cacheable online, you don’t need to do
anything 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 Example
var 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 Server
var 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 Rettig
pascal@cykod.com

Mais conteúdo relacionado

Mais procurados

Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Charles Nutter
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architectureJung Kim
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaCharles Nutter
 
PyParis2017 / Function-as-a-service - a pythonic perspective on severless com...
PyParis2017 / Function-as-a-service - a pythonic perspective on severless com...PyParis2017 / Function-as-a-service - a pythonic perspective on severless com...
PyParis2017 / Function-as-a-service - a pythonic perspective on severless com...Pôle Systematic Paris-Region
 
Python高级编程(二)
Python高级编程(二)Python高级编程(二)
Python高级编程(二)Qiangning Hong
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference CountingGiuseppe Arici
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopSaša Tatar
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
Joblib for cloud computing
Joblib for cloud computingJoblib for cloud computing
Joblib for cloud computingAlexandre Abadie
 
JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011Charles Nutter
 
Objective-C Is Not Java
Objective-C Is Not JavaObjective-C Is Not Java
Objective-C Is Not JavaChris Adamson
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6Fiyaz Hasan
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleSaúl Ibarra Corretgé
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationIvan Dolgushin
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Expressjguerrero999
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」matuura_core
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleTom Croucher
 

Mais procurados (20)

Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architecture
 
【Unity】Scriptable object 入門と活用例
【Unity】Scriptable object 入門と活用例【Unity】Scriptable object 入門と活用例
【Unity】Scriptable object 入門と活用例
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
PyParis2017 / Function-as-a-service - a pythonic perspective on severless com...
PyParis2017 / Function-as-a-service - a pythonic perspective on severless com...PyParis2017 / Function-as-a-service - a pythonic perspective on severless com...
PyParis2017 / Function-as-a-service - a pythonic perspective on severless com...
 
Python高级编程(二)
Python高级编程(二)Python高级编程(二)
Python高级编程(二)
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Joblib for cloud computing
Joblib for cloud computingJoblib for cloud computing
Joblib for cloud computing
 
Theads services
Theads servicesTheads services
Theads services
 
JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011
 
Objective-C Is Not Java
Objective-C Is Not JavaObjective-C Is Not Java
Objective-C Is Not Java
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio module
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code Generation
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 

Semelhante a Javascript Everywhere: Debugging, Optimizing, Local Storage, Offline Storage and Server Side JS

Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript MisunderstoodBhavya Siddappa
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsYnon Perek
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerabilityCsw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerabilityCanSecWest
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.xYiguang Hu
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformationLars Marius Garshol
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}.toster
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersJavan Rasokat
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 

Semelhante a Javascript Everywhere: Debugging, Optimizing, Local Storage, Offline Storage and Server Side JS (20)

Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
 
Performance patterns
Performance patternsPerformance patterns
Performance patterns
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
NodeJS
NodeJSNodeJS
NodeJS
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerabilityCsw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Node.js
Node.jsNode.js
Node.js
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA Testers
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 

Mais de Pascal Rettig

Web Typography for Front End Developers
Web Typography for Front End DevelopersWeb Typography for Front End Developers
Web Typography for Front End DevelopersPascal Rettig
 
The State of Front End Web Development 2011
The State of Front End Web Development 2011The State of Front End Web Development 2011
The State of Front End Web Development 2011Pascal Rettig
 
3D in the Browser via WebGL: It's Go Time
3D in the Browser via WebGL: It's Go Time 3D in the Browser via WebGL: It's Go Time
3D in the Browser via WebGL: It's Go Time Pascal Rettig
 
Vector Graphics on the Web: SVG, Canvas, CSS3
Vector Graphics on the Web: SVG, Canvas, CSS3Vector Graphics on the Web: SVG, Canvas, CSS3
Vector Graphics on the Web: SVG, Canvas, CSS3Pascal Rettig
 
Cracking the Customer Acquisition Nut
Cracking the Customer Acquisition NutCracking the Customer Acquisition Nut
Cracking the Customer Acquisition NutPascal Rettig
 
HTML5 Space Invaders
HTML5 Space InvadersHTML5 Space Invaders
HTML5 Space InvadersPascal Rettig
 

Mais de Pascal Rettig (9)

Web Typography for Front End Developers
Web Typography for Front End DevelopersWeb Typography for Front End Developers
Web Typography for Front End Developers
 
Javascript FTW
Javascript FTWJavascript FTW
Javascript FTW
 
The State of Front End Web Development 2011
The State of Front End Web Development 2011The State of Front End Web Development 2011
The State of Front End Web Development 2011
 
Semantic chop
Semantic chopSemantic chop
Semantic chop
 
3D in the Browser via WebGL: It's Go Time
3D in the Browser via WebGL: It's Go Time 3D in the Browser via WebGL: It's Go Time
3D in the Browser via WebGL: It's Go Time
 
Mobile HTML5
Mobile HTML5Mobile HTML5
Mobile HTML5
 
Vector Graphics on the Web: SVG, Canvas, CSS3
Vector Graphics on the Web: SVG, Canvas, CSS3Vector Graphics on the Web: SVG, Canvas, CSS3
Vector Graphics on the Web: SVG, Canvas, CSS3
 
Cracking the Customer Acquisition Nut
Cracking the Customer Acquisition NutCracking the Customer Acquisition Nut
Cracking the Customer Acquisition Nut
 
HTML5 Space Invaders
HTML5 Space InvadersHTML5 Space Invaders
HTML5 Space Invaders
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 

Último (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

Javascript Everywhere: Debugging, Optimizing, Local Storage, Offline Storage and Server Side JS

  • 1. Javascript Everywhere Online, Offline and on the Server Pascal Rettig http://www.cykod.com @cykod
  • 2. Topics • Debugging Javascript • Optimizing Javascript • Local Storage • Offline Storage • Server side Javascript + Web Sockets (Time permitting)
  • 3. Debugging Javascript Or, alert(“Can only take you so far”);
  • 5. Other browsers • Chrome and IE8 have similar tools to Firebug built in. • Tools -> Developer Tools in both
  • 6. Firebug 101 • Inspecting • Modifying • Tracking resources
  • 7. Firebug 102 Getting rid of alert(...) • Firebug console • console.log(...), console.warn(...), console.error(...) • execute javascript directly from the console • Firebug needs to be open
  • 8. Javascript Debugging • Firebug step debugger • Setting watches • Setting breakpoints • Setting conditional breakpoints
  • 9. The best type of bug...
  • 10. The best type of bug... ... is one that’s caught for you.
  • 11. Javascript is a lax language Your javascript code will only be as rigorous as you are.
  • 12. Consider lint’ing http://javascriptlint.com/ Command line tool by Matthias Miller built on the work done by Douglas Crockford (“JS, the good parts”)
  • 13. Automated Testing Frameworks QUnit - used in JQuery Jasmine - Created by Pivotal Labs, Inspired by RSpec
  • 14. QUnit By John Resig, Founder of JQuery http://docs.jquery.com/Qunit test("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" ); });
  • 15. 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); }); });
  • 16. Optimizing Profiling Javascript Optimization Network Optimization
  • 17. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. - Donald Knuth
  • 18. Javascript Profiling with Firebug
  • 19. Javascript Profiling with Firebug • Click “profile”
  • 20. Javascript Profiling with Firebug • Click “profile” • Wait
  • 21. Javascript Profiling with Firebug • Click “profile” • Wait • Click “profile” again
  • 22. 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?
  • 23. Arrays http://jsperf.com/array-selection-methods/2 var 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; i for (i = 0; i < len; i++) { ++) {  arr.push(i)  arr[i] = i } }
  • 24. Object Creation http://jsperf.com/object-initialization-patterns-test var 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(); }
  • 25. Double check your intuition... • http://jsperf.com • http://jsfiddle.net/
  • 27. 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
  • 28. Taking Javascript Home • Local Storage • Offline storage
  • 29. Local Storage Store data on the client for later use.
  • 30. Isn’t that just like a cookie?
  • 31. Isn’t that just like a cookie? Yes and no
  • 32. Local Storage vs. Cookies Sent Available Size Number Each on Limit Limit Request? Server? Local 5-10MB N/A No No Storage Cookies 4K 20 Yes Yes
  • 33. 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
  • 34. Testing for Local Storage Testing directly (From Dive Into HTML5) function supports_local_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch(e){ return false; } } Using Modernizr if (Modernizr.localstorage) { // Local Storage available }
  • 35. Using Local Storage // Add an item to local storage try { localStorage.setItem(identifierString, valueString); localStorage.identifierString = valueString; } catch(e) { if (e == QUOTA_EXCEEDED_ERR) { /* Do something */ } } // Retrieve an item localStorage.getItem(identifierString); localStorage.identifierString; // Remove an item localStorage.removeItem(identifierString); delete localStorage[identifierString]; // Clear the entire per-domain DB localStorage.clear();
  • 36. Strings only... Probably want to create an API on top of localStorage Storage.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/
  • 37. 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
  • 38. Other HTML5 Storage Options • sessionStorage - same as localStorage but per tab • Web SQL - Provides SQLite compatible DB storage - WebKit only - good for mobile sync
  • 40. Why? • Make apps available offline (Duh!) • Make mobile apps that sync when networked • Force browsers to keep assets available
  • 41. The set-up 1. Add a manifest file to your HTML: <html manifest="/cache.manifest"> 2. Make sure your manifest is served with: AddType text/cache-manifest .manifest 3. Create the manifest listing cached files: CACHE MANIFEST /style.css /application.js /images/image1.jpg ... /images/imageN.jpg 4. Listen for events on window.applicationCache
  • 42. The Events on window.applicationCache Event When checking First event, checking for a manifest noupdate Manifest hasn’t changed downloading Downloading the update progress Periodically while downloading Everything downloading, application cached cached A new cached is available, use updateready swapCache() to swap out Something returned a 404, so cache obsolete is being deleted error Something, somewhere went wrong
  • 43. But... If you have a simple app that you just want to be cacheable online, you don’t need to do anything special
  • 44. 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.
  • 46. Why? • Leverage existing javascript codebase • Async good support for realtime and Websockets
  • 47. Introducing Node.js http://nodejs.org/ • Built on Embedded Google V8 Engine • Check out nodejs.com for installation • Single threaded async • Lots of callbacks
  • 48. 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
  • 49. Simplest Example var 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/');
  • 50. WebSockets: the problem • Want realtime messaging • Not supported in older browsers • Removed from FF4 for the time being
  • 51. WebSockets: a solution http://socket.io/ •Supports native WebSockets •Has a fallback for flash •Handles it all for you
  • 52. The Server var 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'); }); });
  • 53. 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>
  • 54. Thanks! Pascal Rettig pascal@cykod.com

Notas do Editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n