SlideShare a Scribd company logo
High Performance Ajax Applications Julien Lecomte http://www.julienlecomte.net/blogfiles/performance/ajax-perf.ppt http://www.slideshare.net/julien.lecomte/high-performance-ajax-applications
Part 1 Developing For High Performance
Planning and designing for high performance Plan for performance from day 1 Work closely with designers and product managers Understand design rationale Explain the tradeoffs between design and performance Offer alternatives and show what is possible (prototype) Challenge yourself to implement challenging designs (don't just say no) Help simplify the design and interaction if needed (compromise)
Engineering high performance: A few basic rules Less is more Don’t do anything unnecessary. Don’t do anything until it becomes absolutely necessary. Break the rules Make compromises and break best practices, but only as a last resort! Work on improving perceived performance Users can deal with some reasonable amount of slowness if: They are informed appropriately that an operation is pending. The user interface remains reactive at all time. Cheat whenever you can by first updating the UI and then do the work. Need to “lock” all or part of the user interface.

Recommended for you

Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge

The document summarizes Guillaume Laforge's background and expertise in Groovy and JVM technologies. It then provides an overview of the rich Groovy ecosystem, including frameworks like Grails and Griffon for building applications, GPars for concurrency, and tools for testing, building projects, and interacting with web services. Specific examples are given of how to create a simple console application in Griffon and use various concurrency abstractions in GPars.

gradleeasybgrails
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides

This document summarizes techniques for optimizing Angular application performance, including ahead of time compilation, lazy loading, change detection strategies, avoiding memory leaks, and server side rendering. It provides code examples and compares boot times between different configurations. The techniques can improve first meaningful paint time by up to 86% compared to the default configuration.

angular optimization
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"

Мне нравится использовать React. Данная библиотека – отличное решение для многих задач, так как она не навязывает конкретный паттерн или архитектуру. Разработчик сам решает что лучше для той или иной ситуации. Существует множество уже готовых архитектурных решений. Большинство выбирает Redux. Существует множество библиотек использующее идеи FRP, например Calmm или MobX. Как результат, получаем много подходов, решающие одну и туже задачу. В своем докладе хочу поговорить о различных архитектурных решениях, пос��отреть на плюсы и минусы той или иной библиотеки, и прийти к консенсусу.

fwdaysjsframeworks
Measuring performance Test performance using a setup similar to your users’ environment Profile your code during development Automate profiling/performance testing Keep historical records of how features perform Consider keeping some (small amount of) profiling code in production
Part 2 High Performance Page Load
Yahoo!'s Exceptional Performance rules Make Fewer HTTP Requests Use a Content Delivery Network Add an Expires Header Gzip Components (including JS!) Put CSS at the Top Move Scripts to the Bottom Avoid CSS Expressions Make JavaScript and CSS External Reduce DNS Lookups Minify JavaScript Avoid Redirects Remove Duplicate Scripts Configure ETags Make Ajax Cacheable See  http://developer.yahoo.com/performance/  for more information. A web page works in 3 (sometimes imbricated) stages: load render run These rules cover  mostly  the first stage.
Asset optimization Minify CSS and JavaScript files: Use the YUI Compressor [  http://developer.yahoo.com/yui/compressor/  ] Stay away from so-called advanced compression schemes - like Packer Combine CSS and JavaScript files: At build time [  http://www.julienlecomte.net/blog/2007/09/16/  ] At run time Optimize image assets: PngCrush [  http://pmt.sourceforge.net/pngcrush/  ] PngOptimizer [  http://psydk.org/PngOptimizer.php  ] etc.

Recommended for you

Intro to JavaScript Testing
Intro to JavaScript TestingIntro to JavaScript Testing
Intro to JavaScript Testing

This document discusses JavaScript testing and provides an introduction to test-driven development (TDD) and behavior-driven development (BDD). It describes why software projects fail when code is not tested, the benefits of testing code, and demonstrates writing tests using Mocha and Expect.js for a user creation function.

node.jsbddexpectjs
Let's migrate to Swift 3.0
Let's migrate to Swift 3.0Let's migrate to Swift 3.0
Let's migrate to Swift 3.0

This document discusses strategies for migrating code from Swift 2.x to Swift 3.0. It recommends first migrating dependencies using tools like CocoaPods and Carthage. It then recommends using Xcode's migration assistant to fix issues, while also preparing code templates beforehand using tools like SwiftGen. Some challenges discussed include changes made automatically by the migrator, optional comparators being removed, and Grand Central Dispatch API changes. References for further information on the Swift 3 migration are provided.

cocoaheadsiosswift
Dan Webb Presentation
Dan Webb PresentationDan Webb Presentation
Dan Webb Presentation

The document discusses unobtrusive JavaScript and the UJS plugin for Rails. It describes separating JavaScript behavior from HTML content and CSS styling. The UJS plugin allows defining behaviors via CSS selectors and keeping scripts in external files. Examples are given of attaching remote behaviors to links and forms using the UJS plugin.

Reduce unminified code size Loading and parsing HTML, CSS and JavaScript code is costly. Be concise and write less code. Make good use of JavaScript libraries. Consider splitting your large JavaScript files into smaller files (bundles) when the parsing and compilation of the script takes an excessive amount of time ( Firefox bug #313967 ) Load code (HTML, CSS and JavaScript) on demand (a.k.a “lazy loading”) See  http://ajaxpatterns.org/On-Demand_Javascript Use the YUI Loader Dojo's package system JSAN Import System
Optimize initial rendering (1/4) Miscellaneous tips... Consider rendering the first view on the server: Be aware of the added page weight You will still need to attach event handlers once the DOM is ready Close Your HTML Tags to Speed Up Parsing: Implicitly closed tags add cost to HTML parsing http://msdn2.microsoft.com/en-us/library/ms533020.aspx#Close_Your_Tags Consider flushing the apache buffer very early on: The download of external CSS files (should be at the top of the page!) may get a head start. May not influence the rendering speed however. Browsers buffer their input before displaying it. Load only essential assets / load assets on a delay or on demand Use the YUI Image Loader
Optimize initial rendering (2/4) Don’t always wait for  onload ... Most DOM operations can be accomplished before the onload event has fired. If you have control over where your code is going to be inserted in the page, write your init code in a  <script>  block located right before the closing  </body>  tag. Otherwise, use the YUI Event utility’s  onDOMReady  method: YAHOO.util.Event.onDOMReady( function  () { // Do something here... // e.g., attach event handlers. });
Optimize initial rendering (3/4) Post-load script loading A well designed site should be fully functional, even without JavaScript enabled. Therefore, you may be able to load scripts on a delay. Doing so benefits the loading of other assets (style sheets, images, etc.) Which makes your site load faster Right before the closing  </body>  tag, insert the following: <script> window.onload =  function  () { var  script = document.createElement( &quot;script&quot; ); script.src = ...; document.body.appendChild(script); }; </script>

Recommended for you

Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps

1. The document discusses using JHipster, an open source tool, to generate Angular and Spring Boot applications. It demonstrates generating both monolithic and microservices applications. 2. Key features of JHipster covered include generating entities, internationalization, and deployment options. Running and developing applications in both development and production modes is explained. 3. Examples are provided of generating sample applications using JHipster's online generator and locally installed generator. This includes reviewing the generated code and application structure.

angular2jhipsterjava
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps

Web pages can get very complex and slow. In this talk, I share how we solve some of these problems at LinkedIn by leveraging composition and streaming in the Play Framework. This was my keynote for Ping Conference 2014 ( http://www.ping-conf.com/ ): the video is on ustream ( http://www.ustream.tv/recorded/42801129 ) and the sample code is on github ( https://github.com/brikis98/ping-play ).

play frameworkcompositionstreaming
React & The Art of Managing Complexity
React &  The Art of Managing ComplexityReact &  The Art of Managing Complexity
React & The Art of Managing Complexity

React is a UI library that is changing the way web applications are written. While there are many benefits to using React, managing an application's complexity as it scales is one of the most powerful.

reactjsjavascript
Optimize initial rendering (4/4) Conditional preloading Preloading assets (JavaScript, CSS, Images, etc.) has the potential to really enhance the user experience. However, one must be smart about when the preloading takes place. Otherwise, the preloading may actually worsen the user experience... http://www.sitepoint.com/article/web-site-optimization-steps/3 Try it at  http://search.yahoo.com/
Part 3 High Performance JavaScript
Reduce the amount of symbolic look-up: The scope chain (1/2) var  g =  7 ; function  f(a) { var  v =  8 ; x = v + a + g; } f(6); parent Look-up is performed every time a variable is accessed. Variables are resolved backwards from most specific to least specific scope.
Reduce the amount of symbolic look-up: The scope chain (2/2) Therefore, declare (with the  var  keyword) and use variables in the same scope whenever possible, and avoid global variables at all costs. Never use the  with  keyword, as it prevents the compiler from generating code for fast access to local variables (traverse the object prototype chain first, and then up the scope chain, and so on) Cache the result of expensive look-ups in local variables: var  arr = ...; var  globalVar =  0 ; ( function  () { var  i; for (i =  0 ; i < arr.length; i++) { globalVar++; } })(); var  arr = ...; var  globalVar =  0 ; ( function  () { var  i, l, localVar; l = arr.length; localVar = globalVar; for (i =  0 ; i < l; i++) { localVar++; } globalVar = localVar; })(); (faster on all A-grade browsers)

Recommended for you

Zenly - Reverse geocoding
Zenly - Reverse geocodingZenly - Reverse geocoding
Zenly - Reverse geocoding

Architecture d’un reverse geocoder, pour aller au delà des limites de l’objet de base par Laurent Cerveau de Zenly.

cocoaheads
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma

The document discusses unit testing in Angular with Karma. It provides examples of UX patterns in Angular like binding elements to variables, lists, and click handlers. It also covers what controllers and scopes are and examples of testing components in Angular like services, factories, and UI elements. Hands-on examples are provided for setting up a test environment and writing tests.

mobile designconferencemodevux
So how do I test my Sling application?
 So how do I test my Sling application? So how do I test my Sling application?
So how do I test my Sling application?

Developing a Sling application is only half the story - or perhaps even less. Automated testing is of great importance for insuring code quality and reducing regression risk. Sling presents an interesting challenge, as its technology stack does not get as much attention as more mainstream ones. As such, we had the pleasure of developing our own patterns and testing tools, while integrating the foundations that already existed. This presentation will walk through the various available tools and show how they can be used to cover a Sling-based application.

sling apache osgi jcr aem
Reduce the amount of symbolic look-up: The prototype chain function  A () {} A.prototype.prop1 = ...; function  B () { this .prop2 = ...; } B.prototype =  new  A(); var  b =  new  B(); B.prototype Accessing members bound to the primary object is about 25% faster than accessing members defined anywhere in the prototype chain. The longer the traversal of the prototype chain, the slower the look-up.
Optimize object instantiation If you need to create many objects, consider adding members to the prototype instead of adding them to each individual object in the object constructor (properties are bound once, to the prototype object) This also reduces memory consumption. However, it slows down the look-up of object members. function  Foo () {...} Foo.prototype.bar =  function  () {...}; function  Foo () { this .bar =  function  () {...}; }
Don’t use  eval ! The string passed to  eval  (and its relatives, the  Function  constructor and the  setTimeout  and  setInterval  functions) needs to be compiled and interpreted. Extremely slow! Never pass a string to the  setTimeout  and  setInterval  functions. Instead, pass an anonymous function like so: setTimeout( function  () { // Code to execute on a timeout },  50 ); Never use  eval  and the  Function  constructor (except in some extremely rare cases, and only in code blocks where performance is not critical)
Optimize string concatenation On Internet Explorer (JScript), concatenating two strings causes a new string to be allocated, and the two original strings to be copied: var  s =  “xxx”  +  “yyy” ; s +=  “zzz” ; Therefore, it is much faster on Internet Explorer to append strings to an array, and then use  Array.join  (don’t use this for simple concatenations!) var  i, s =  “” ; for (i =  0 ; i <  10000 ; i++) { s +=  “x” ; } var  i, s = []; for (i =  0 ; i <  10000 ; i++) { s[i] =  “x” ; } s = s.join( “” ); Other JavaScript engines (WebKit, SpiderMonkey) have been optimized to handle string concatenations by doing a  realloc  +  memcpy  whenever possible. Use the YUI Compressor!

Recommended for you

OHHttpStubs
OHHttpStubsOHHttpStubs
OHHttpStubs

This document discusses OHHTTPStubs, a library for stubbing network requests in iOS unit and integration tests. It provides examples of how to use OHHTTPStubs to stub requests and responses using files, JSON objects or code. The document also presents two use cases - refactoring existing network code to make it testable, and stubbing requests for features that depend on not-yet-implemented web services, to allow development and testing ahead of server integration.

iosmockup
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3

The document discusses how PHP 5.3 changes the implementation of common design patterns like the Singleton pattern and Observer pattern through the use of anonymous functions. It provides code examples of implementing these patterns in PHP 4/5.0-5.2 versus PHP 5.3 using features like closures, late static binding, and __invoke(). The document also proposes building a dependency injection container in PHP 5.3 using anonymous functions to describe object creation without instantiating objects. This approach results in a simple yet fully-featured dependency injector implementation in around 40 lines of code.

phpobserverdependency injection
Basic testing with selenium
Basic testing with seleniumBasic testing with selenium
Basic testing with selenium

The document discusses using Selenium IDE to record and play test cases for web applications. It provides an overview of key web technologies like HTTP, HTML, DOM, CSS, and JavaScript. It then covers how to install and use Selenium IDE to record tests, modify test cases, handle random input, and run tests on a standalone Selenium server in different browsers.

developmentseleniumweb
Optimize regular expressions Don’t use the  RegExp  constructor, unless your regular expression is assembled at runtime. Instead, use regular expression literals. Use the  test  method if all you want to do is test for a pattern (the  exec  method carries a small performance penalty) Use non-capturing groups  (?: ... ) Stick to simple patterns. If your regular expression looks like the following, reconsider... if ( /loaded|complete/ .test(document.readyState)) {...} (?:(?:)?[])*(?:(?:(?:[^()<>@,;:&quot;.00-31]+(?:(?:(?:)?[])+||(?=[&quot;()<>@,;:&quot;.]))|&quot; (?:[^amp;quot;]|.|(?:(?:)?[]))*&quot;(?:(?:)?[])*)(?:(?:(?:)?[])*(?:[^()<>@,;:&quot;.00-31 ]+(?:(?:(?:)?[])+||(?=[&quot;()<>@,;:&quot;.]))|&quot;(?:[^amp;quot;]|.|(?:(?:)?[]))*&quot;(?:(?:)?[]) *))*@(?:(?:)?[])*(?:[^()<>@,;:&quot;.00-31]+(?:(?:(?:)?[])+||(?=[&quot;()<>@,;:&quot;.]))| ([^]|.)*(?:(?:)?[])*)(?:(?:(?:)?[])*(?:[^()<>@,;:&quot;.00-31]+(?:(?:(?:)? [])+||(?=[&quot;()<>@,;:&quot;.]))|([^]|.)*(?:(?:)?[])*))*|(?:[^()<>@,;:&quot;.00- 31]+(?:(?:(?:)?[])+||(?=[&quot;()<>@,;:&quot;.]))|&quot;(?:[^amp;quot;]|.|(?:(?:)?[]))*&quot;(?:(?:)?[ ])*)*lt;(?:(?:)?[])*(?:@(?:[^()<>@,;:&quot;.00-31]+(?:(?:(?:)?[])+||(?=[&quot;()<>@,;:&quot;. ]))|([^]|.)*(?:(?:)?[])*)(?:(?:(?:)?[])*(?:[^()<>@,;:&quot;.00-31]+(?:(?:(?: )?[])+||(?=[&quot;()<>@,;:&quot;.]))|([^]|.)*(?:(?:)?[])*))*(?:,@(?:(?:)?[]))
Caching Caching can be justified by: High cost (CPU or network latency) associated with getting a value Value will be read many times And will not change often! Increases memory consumption    tradeoff Memoization: var  fn = ( function  () { var  b =  false , v; return   function  () { if  (!b) { v = ...; b =  true ; } return  v; }; })(); function  fn () { if  (!fn.b) { fn.v = ...; fn.b =  true ; } return  fn.v; } var  fn =  function  () { var  v = ...; return  (fn =  function  () { return  v; })(); }; Module pattern Store value in function object Lazy function definition
How to handle long running JavaScript processes (1/2) During long running JavaScript processes, the entire browser UI is frozen Therefore, to maintain a decent user experience, make sure that JavaScript threads never take more than ~ 300 msec (at most) to complete. You can break long running processes into smaller units of work, and chain them using  setTimeout . You can also process the data on the server. More info at  http://www.julienlecomte.net/blog/2007/10/28 Demo
How to handle long running JavaScript processes (2/2) function  doSomething (callbackFn) { // Initialize a few things here... ( function  () { // Do a little bit of work here... if  ( termination condition ) { // We are done callbackFn(); }  else  { // Process next chunk setTimeout(arguments.callee, 0); } })(); }

Recommended for you

Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework

Video: https://www.youtube.com/watch?v=b6yLwvNSDck Here's the showdown you've been waiting for: Node.js vs Play Framework. Both are popular open source web frameworks that are built for developer productivity, asynchronous I/O, and the real time web. But which one is easier to learn, test, deploy, debug, and scale? Should you pick Javascript or Scala? The Google v8 engine or the JVM? NPM or Ivy? Grunt or SBT? Two frameworks enter, one framework leaves. This is the English version of the presentation. For the version with Japanese subtitles, see http://www.slideshare.net/brikis98/nodejs-vs-play-framework-with-japanese-subtitles

javascriptnode.jsplay framework
Acomer
AcomerAcomer
Acomer

El fotógrafo Peter Menzel viajó por el mundo y fotografió a 30 familias de 24 países diferentes, junto con la comida que consumirían en una semana y sus gastos. Su libro "Hungry Planet" muestra estas fotos y revela grandes diferencias entre los productos, tamaños de familias y gastos semanales que van desde $5.03 en Bután hasta $500.07 en Alemania.

De achtbaan der E Commerce 2.0: Losing control(oude versie)
De achtbaan der E Commerce 2.0: Losing control(oude versie)De achtbaan der E Commerce 2.0: Losing control(oude versie)
De achtbaan der E Commerce 2.0: Losing control(oude versie)

Een presentatie over de verschuiving van de e-commercebranche naar e-commerce 2.0

Miscellaneous tips (1/2) Primitive operations are often faster than the corresponding function calls: var  a =  1 , b =  2 , c; c = Math.min(a, b); c = a < b ? a : b; If possible, avoid using  try...catch  in performance-critical sections: var  i; for  (i =  0 ; i <  100000 ; i++) { try  { ... }  catch  (e) { ... } } var  i; try  { for  (i =  0 ; i <  100000 ; i++) { ... } }  catch  (e) { ... } myArray.push(value); myArray[myArray.length] = value; myArray[idx++] = value;
Miscellaneous tips (2/2) If possible, avoid  for...in  in performance-critical sections: var  key, value; for  (key in myArray) { value = myArray[key]; ... } var  i, value, length = myArray.length; for  (i =  0 ; i < length; i++) { value = myArray[i]; ... } Branch outside, not inside, whenever the branching condition does not change: function  fn () { if  (...) { ... }  else  { ... } } var  fn; if  (...) { fn =  function  () {...}; }  else  { fn =  function  () {...}; }
Part 4 High Performance Dynamic HTML
Document tree modification Using  innerHTML var  i, j, el, table, tbody, row, cell; el = document.createElement( &quot;div&quot; ); document.body.appendChild(el); table = document.createElement( &quot;table&quot; ); el.appendChild(table); tbody = document.createElement( &quot;tbody&quot; ); table.appendChild(tbody); for  (i =  0 ; i <  1000 ; i++) { row = document.createElement( &quot;tr&quot; ); for  (j =  0 ; j <  5 ; j++) { cell = document.createElement( &quot;td&quot; ); row.appendChild(cell); } tbody.appendChild(row); } var  i, j, el, idx, html; idx =  0 ; html = []; html[idx++] =  &quot;<table>&quot; ; for  (i =  0 ; i <  1000 ; i++) { html[idx++] =  &quot;<tr>&quot; ; for  (j =  0 ; j <  5 ; j++) { html[idx++] =  &quot;<td></td>&quot; ; } html[idx++] =  &quot;</tr>&quot; ; } html[idx++] =  &quot;</table>&quot; ; el = document.createElement( &quot;div&quot; ); document.body.appendChild(el); el.innerHTML = html.join( &quot;&quot; ); ( much  faster on all A-grade browsers) Warning: See  http://www.julienlecomte.net/blog/2007/12/38/

Recommended for you

Tirrell
TirrellTirrell
Tirrell

This document summarizes research on electrostatic complexes in polymer materials science. It discusses using non-covalent interactions like π-stacking, coordination via metals, and hydrogen bonding to build supermolecular structures from polymer assemblies. It also describes techniques like layer-by-layer assembly and complex coacervation to encapsulate and pattern materials. The research aims to better understand parameters affecting polyelectrolyte brush structures and interactions through experiments using surface force apparatus.

Copyleft project
Copyleft projectCopyleft project
Copyleft project

Our groups presentation of the expression "Copyleft"

Document tree modification Using  cloneNode var  i, j, el, table, tbody, row, cell; el = document.createElement( &quot;div&quot; ); document.body.appendChild(el); table = document.createElement( &quot;table&quot; ); el.appendChild(table); tbody = document.createElement( &quot;tbody&quot; ); table.appendChild(tbody); for  (i =  0 ; i <  1000 ; i++) { row = document.createElement( &quot;tr&quot; ); for  (j =  0 ; j <  5 ; j++) { cell = document.createElement( &quot;td&quot; ); row.appendChild(cell); } tbody.appendChild(row); } var  i, el, table, tbody, template, row, cell; el = document.createElement( &quot;div&quot; ); document.body.appendChild(el); table = document.createElement( &quot;table&quot; ); el.appendChild(table); tbody = document.createElement( &quot;tbody&quot; ); table.appendChild(tbody); template = document.createElement( &quot;tr&quot; ); for  (i =  0 ; i <  5 ; i++) { cell = document.createElement( &quot;td&quot; ); template.appendChild(cell); } for  (i =  0 ; i <  1000 ; i++) { row = template.cloneNode(true); tbody.appendChild(row); } (faster on all A-grade browsers – sometimes  much  faster) Warning: expando properties/attached event handlers are lost!
Document tree modification Using DocumentFragment A DocumentFragment (DOM Level 1 Core) is a lightweight Document object. It supports only a subset of the regular DOM methods and properties. IE’s implementation of the DocumentFragment interface does not comply with the W3C specification and returns a regular Document object. var  i, j, el, table, tbody, row, cell, docFragment; docFragment = document.createDocumentFragment(); el = document.createElement( &quot;div&quot; ); docFragment.appendChild(el); table = document.createElement( &quot;table&quot; ); el.appendChild(table); tbody = document.createElement( &quot;tbody&quot; ); table.appendChild(tbody); for  (i =  0 ; i <  1000 ; i++) { ... } document.body.appendChild(docFragment);
Limit the number of event handlers (1/2) Attaching an event handler to hundreds of elements is very costly Multiplying event handlers augments the potential for memory leaks Solution: Use  event delegation , a technique that relies on  event bubbling <div id= &quot;container&quot; > <ul> <li id= &quot;li-1&quot; > List Item 1 </li> <li id= &quot;li-2&quot; > List Item 2 </li> <li id= &quot;li-3&quot; > List Item 3 </li> <li id= &quot;li-4&quot; > List Item 4 </li> <li id= &quot;li-5&quot; > List Item 5 </li> ... </ul> </div> div#container ul li#li- x text node
Limit the number of event handlers (2/2) YAHOO.util.Event.addListener( &quot;container&quot; ,  &quot;click&quot; ,  function  (e) { var  el = YAHOO.util.Event.getTarget(e); while (el.id !==  &quot;container&quot; ) { if (el.nodeName.toUpperCase() ===  &quot;LI&quot; ) { // Do something here... break; } else { el = el.parentNode; } } });

Recommended for you

Cuento De Hadas 2
Cuento De Hadas 2Cuento De Hadas 2
Cuento De Hadas 2

El documento describe diferentes tipos de hadas japonesas, incluyendo hadas Kawasaki que viven en ciénagas y hacen pociones amorosas, hadas florales que habitan en flores y les dan color o acompañan novias, hadas estelares que hacen constelaciones florales, y hadas del aire, agua, amanecer, noche, y otras más que viven en diferentes elementos naturales y se dedican a tareas relacionadas.

China Winter Snow 1
China Winter Snow 1China Winter Snow 1
China Winter Snow 1

The document repeatedly lists the phrase "Jokes.StevenWongBlog.com" over 50 times without any other text or context. It provides no clear information about the content or purpose beyond mentioning a blog related to jokes.

EI Tibet
EI TibetEI Tibet
EI Tibet
Limiting reflows Reflows happen whenever the DOM tree is manipulated. Browsers have optimizations you may take advantage of to minimize reflow: Modifying an invisible element (display:none) does not trigger reflow Modifying an element “off-DOM” does not trigger reflow Batch style changes: Change the value of the style attribute using setAttribute (does not work on Internet Explorer) Example: Change the value of the cssText property of the style object. Example: More maintainable: Change the CSS class name of an element. Example: el.style.cssText =  &quot;display:block;width:auto;height:100px;...&quot; ; YAHOO.util.Dom.replaceClass(el,  &quot;foo&quot; ,  &quot;bar&quot; ); el.setAttribute( &quot;style&quot; ,  &quot;display:block;width:auto;height:100px;...&quot; );
Miscellaneous tips... Consider using the  onmousedown  event instead of the  onclick  event Get a head start by making use of the small delay between the time a user presses the mouse button and the time he/she releases it. “ Downshift your code”: throttle frequent and expensive actions See  http://yuiblog.com/blog/2007/07/09/downshift-your-code/
Part 5 High Performance Layout and CSS
Miscellaneous tips... Use CSS Sprites for Snappy Image Replacement. Avoid using JavaScript for layout. window.onresize is throttled... Use pure CSS instead! Side benefits: improves maintainability, degrades more gracefully, etc. Avoid using Internet Explorer expressions Expressions are constantly evaluated in order to react to environment changes. There are ways to more safely use expressions, but in general, you shouldn’t need/use them. Avoid using Internet Explorer filters (or keep their use to a minimum) Optimize Table Layout Goal: allow the rendering engine to start rendering a table before it has received all the data Use table-layout:fixed Explicitly define a COL element for each column Set the WIDTH attribute on each col Optimize your CSS selectors  [  http://developer.mozilla.org/en/docs/Writing_Efficient_CSS  ]

Recommended for you

Fuerza
FuerzaFuerza
Fuerza

La fuerza se mide en newtons y es la acción capaz de modificar el estado de movimiento o reposo de un cuerpo. La fuerza puede poner un cuerpo en movimiento al empujarlo o jalarlo, y la aceleración que alcanza un cuerpo depende directamente de la fuerza aplicada. La masa mide la cantidad de materia contenida en un cuerpo y está relacionada a su inercia, por lo que se requiere más fuerza para mover objetos con mayor masa.

Escoex Publicidad Elanunciante Dia Uno
Escoex Publicidad Elanunciante Dia UnoEscoex Publicidad Elanunciante Dia Uno
Escoex Publicidad Elanunciante Dia Uno

Este documento resume los conceptos clave de la industria publicitaria, incluyendo los roles del anunciante, las agencias y los medios. Describe la organización típica de un departamento de marketing, con funciones como el director de marketing, jefe de producto y jefe de medios. También resume los derechos y responsabilidades legales del anunciante según la Ley General de Publicidad española.

Part 6 High Performance Ajax
Ajax Best Practices Never resort to using synchronous XMLHttpRequest http://yuiblog.com/blog/2006/04/04/synchronous-v-asynchronous/ Asynchronous programming model slightly more complicated. Need to lock all or part of the UI while the transaction is pending. Programmatically handle network timeouts. Solution: Use the YUI Connection Manager: var  callback = { success:  function  () {  /* Do something */  }, failure:  function  () {  /* Do something */  }, timeout:  5000 }; YAHOO.util.Connect.asyncRequest( &quot;GET&quot; , url, callback);
Improving perceived network latency using the optimistic pattern If the data is validated locally (on the client, using JavaScript) before being sent to the server, the request will be successful in 99.9% of the cases. Therefore, in order to optimize the user experience, we should assume a successful outcome and adopt the following pattern: Update the UI when the request gets sent. Lock the UI/data structures with the finest possible granularity. Let the user know that something is happening. Let the user know why a UI object is locked. Unlock the UI/data structures when the outcome is successful. Handle error cases gracefully.
Miscellaneous tips... Be aware of the maximum number of concurrent HTTP/1.1 connections. Multiplex Ajax requests whenever possible, and if your backend supports it. Piggyback unsollicited notifications in a response to an Ajax request. Favor JSON over XML as your data exchange format Accessing a JSON data structure is easier and cheaper than accessing XML data. JSON has less overhead than XML. Push, don’t poll. Use  COMET  to send real-time notifications to the browser. Consider using local storage to cache data locally, request a diff from the server: Internet Explorer’s userData Flash local storage DOM:Storage (WhatWG persistent storage API, implemented in Firefox 2) Google Gears etc.

Recommended for you

Iranian Look Alikes
Iranian Look AlikesIranian Look Alikes
Iranian Look Alikes

The document lists various pairings of people and organizations, some related to Iran and others that are unrelated or nonsensical, including Iranian political and religious figures paired with Hollywood celebrities and technology executives. It expresses a vague feeling that something is wrong and encourages the reader to "See 4 UR Self". The overall content and intent of the document is unclear.

Copyleft
CopyleftCopyleft
Copyleft

powerpoint presentasjon

EdTech Powerpoint
EdTech PowerpointEdTech Powerpoint
EdTech Powerpoint

The document contains 11 citations to Flickr photos related to track and field. The citations provide the photo title, Flickr username of the uploader, and URL for each photo. The photos depict various track and field events, teams, and venues from locations around the world.

Part 7 Performance Tools
Performance Tools YSlow?  [  http://developer.yahoo.com/yslow/  ] Task manager IE Leak Detector a.k.a Drip  [  http://www.outofhanwell.com/ieleak/  ] Stopwatch profiling AjaxView  [  http://research.microsoft.com/projects/ajaxview/  ] JsLex  [  http://rockstarapps.com/pmwiki/pmwiki.php?n=JsLex.JsLex  ] YUI profiler [  http://developer.yahoo.com/yui/profiler/  ] Venkman or Firebug Profiler  [  http://www.getfirebug.com/  ]

More Related Content

What's hot

Thomas Fuchs Presentation
Thomas Fuchs PresentationThomas Fuchs Presentation
Thomas Fuchs Presentation
RubyOnRails_dude
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
Yakov Fain
 
Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"
Fwdays
 
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Guillaume Laforge
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
David Barreto
 
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
Fwdays
 
Intro to JavaScript Testing
Intro to JavaScript TestingIntro to JavaScript Testing
Intro to JavaScript Testing
Ran Mizrahi
 
Let's migrate to Swift 3.0
Let's migrate to Swift 3.0Let's migrate to Swift 3.0
Let's migrate to Swift 3.0
CocoaHeads France
 
Dan Webb Presentation
Dan Webb PresentationDan Webb Presentation
Dan Webb Presentation
RubyOnRails_dude
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps
Yakov Fain
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
Yevgeniy Brikman
 
React & The Art of Managing Complexity
React &  The Art of Managing ComplexityReact &  The Art of Managing Complexity
React & The Art of Managing Complexity
Ryan Anklam
 
Zenly - Reverse geocoding
Zenly - Reverse geocodingZenly - Reverse geocoding
Zenly - Reverse geocoding
CocoaHeads France
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
ExoLeaders.com
 
So how do I test my Sling application?
 So how do I test my Sling application? So how do I test my Sling application?
So how do I test my Sling application?
Robert Munteanu
 
OHHttpStubs
OHHttpStubsOHHttpStubs
OHHttpStubs
CocoaHeads France
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3
Fabien Potencier
 
Basic testing with selenium
Basic testing with seleniumBasic testing with selenium
Basic testing with selenium
Søren Lund
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
Yevgeniy Brikman
 

What's hot (19)

Thomas Fuchs Presentation
Thomas Fuchs PresentationThomas Fuchs Presentation
Thomas Fuchs Presentation
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"
 
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
 
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
Григорий Шехет "Treasure hunt in the land of Reactive frameworks"
 
Intro to JavaScript Testing
Intro to JavaScript TestingIntro to JavaScript Testing
Intro to JavaScript Testing
 
Let's migrate to Swift 3.0
Let's migrate to Swift 3.0Let's migrate to Swift 3.0
Let's migrate to Swift 3.0
 
Dan Webb Presentation
Dan Webb PresentationDan Webb Presentation
Dan Webb Presentation
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
 
React & The Art of Managing Complexity
React &  The Art of Managing ComplexityReact &  The Art of Managing Complexity
React & The Art of Managing Complexity
 
Zenly - Reverse geocoding
Zenly - Reverse geocodingZenly - Reverse geocoding
Zenly - Reverse geocoding
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
 
So how do I test my Sling application?
 So how do I test my Sling application? So how do I test my Sling application?
So how do I test my Sling application?
 
OHHttpStubs
OHHttpStubsOHHttpStubs
OHHttpStubs
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3
 
Basic testing with selenium
Basic testing with seleniumBasic testing with selenium
Basic testing with selenium
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
 

Viewers also liked

Acomer
AcomerAcomer
Acomer
massruiz
 
De achtbaan der E Commerce 2.0: Losing control(oude versie)
De achtbaan der E Commerce 2.0: Losing control(oude versie)De achtbaan der E Commerce 2.0: Losing control(oude versie)
De achtbaan der E Commerce 2.0: Losing control(oude versie)
mailordersolutions
 
Tirrell
TirrellTirrell
Tirrell
ucsb.ira
 
Copyleft project
Copyleft projectCopyleft project
Copyleft project
Bboymali
 
Cuento De Hadas 2
Cuento De Hadas 2Cuento De Hadas 2
Cuento De Hadas 2
guestad0482
 
China Winter Snow 1
China Winter Snow 1China Winter Snow 1
China Winter Snow 1
Steven Wong
 
EI Tibet
EI TibetEI Tibet
EI Tibet
cris
 
Fuerza
FuerzaFuerza
Fuerza
guest45a71d
 
Escoex Publicidad Elanunciante Dia Uno
Escoex Publicidad Elanunciante Dia UnoEscoex Publicidad Elanunciante Dia Uno
Escoex Publicidad Elanunciante Dia Uno
Eladio Bombín Torrens
 
Iranian Look Alikes
Iranian Look AlikesIranian Look Alikes
Iranian Look Alikes
guest6d19c4
 
Copyleft
CopyleftCopyleft
EdTech Powerpoint
EdTech PowerpointEdTech Powerpoint
EdTech Powerpoint
carissa23
 
China's Worst snowstorm
China's Worst snowstorm China's Worst snowstorm
China's Worst snowstorm
guest4df45b
 
internet oggi..e domani
internet oggi..e domaniinternet oggi..e domani
internet oggi..e domani
extrategy
 
Convergencia de la Seguridad
Convergencia de la SeguridadConvergencia de la Seguridad
Convergencia de la Seguridad
S2 Grupo · Security Art Work
 
Web 2.0 E Oltre
Web 2.0 E OltreWeb 2.0 E Oltre
Web 2.0 E Oltre
ronchet
 
Mi viaje a Irlanda
Mi viaje a IrlandaMi viaje a Irlanda
Mi viaje a Irlanda
guest7a922a
 
Pdiusbd11
Pdiusbd11Pdiusbd11
Pdiusbd11
allankliu
 

Viewers also liked (20)

Acomer
AcomerAcomer
Acomer
 
De achtbaan der E Commerce 2.0: Losing control(oude versie)
De achtbaan der E Commerce 2.0: Losing control(oude versie)De achtbaan der E Commerce 2.0: Losing control(oude versie)
De achtbaan der E Commerce 2.0: Losing control(oude versie)
 
Tirrell
TirrellTirrell
Tirrell
 
Copyleft
CopyleftCopyleft
Copyleft
 
Copyleft project
Copyleft projectCopyleft project
Copyleft project
 
Cuento De Hadas 2
Cuento De Hadas 2Cuento De Hadas 2
Cuento De Hadas 2
 
China Winter Snow 1
China Winter Snow 1China Winter Snow 1
China Winter Snow 1
 
EI Tibet
EI TibetEI Tibet
EI Tibet
 
Fuerza
FuerzaFuerza
Fuerza
 
Faq Alice
Faq AliceFaq Alice
Faq Alice
 
Escoex Publicidad Elanunciante Dia Uno
Escoex Publicidad Elanunciante Dia UnoEscoex Publicidad Elanunciante Dia Uno
Escoex Publicidad Elanunciante Dia Uno
 
Iranian Look Alikes
Iranian Look AlikesIranian Look Alikes
Iranian Look Alikes
 
Copyleft
CopyleftCopyleft
Copyleft
 
EdTech Powerpoint
EdTech PowerpointEdTech Powerpoint
EdTech Powerpoint
 
China's Worst snowstorm
China's Worst snowstorm China's Worst snowstorm
China's Worst snowstorm
 
internet oggi..e domani
internet oggi..e domaniinternet oggi..e domani
internet oggi..e domani
 
Convergencia de la Seguridad
Convergencia de la SeguridadConvergencia de la Seguridad
Convergencia de la Seguridad
 
Web 2.0 E Oltre
Web 2.0 E OltreWeb 2.0 E Oltre
Web 2.0 E Oltre
 
Mi viaje a Irlanda
Mi viaje a IrlandaMi viaje a Irlanda
Mi viaje a Irlanda
 
Pdiusbd11
Pdiusbd11Pdiusbd11
Pdiusbd11
 

Similar to High Performance Ajax Applications 1197671494632682 2

Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
David Barreto
 
Silicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NET
Silicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NETSilicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NET
Silicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NET
Mats Bryntse
 
The Web on OSGi: Here's How
The Web on OSGi: Here's HowThe Web on OSGi: Here's How
The Web on OSGi: Here's How
mrdon
 
My 70-480 HTML5 certification learning
My 70-480 HTML5 certification learningMy 70-480 HTML5 certification learning
My 70-480 HTML5 certification learning
Syed Irtaza Ali
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performance
kaven yan
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
kaven yan
 
From Zero to Hero – Web Performance
From Zero to Hero – Web PerformanceFrom Zero to Hero – Web Performance
From Zero to Hero – Web Performance
Sebastian Springer
 
Developing High Performance Web Apps
Developing High Performance Web AppsDeveloping High Performance Web Apps
Developing High Performance Web Apps
Timothy Fisher
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
GDSC UofT Mississauga
 
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnitWriting and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Alex Chaffee
 
Front-end optimisation & jQuery Internals (Pycon)
Front-end optimisation & jQuery Internals (Pycon)Front-end optimisation & jQuery Internals (Pycon)
Front-end optimisation & jQuery Internals (Pycon)
Artur Cistov
 
GWT is Smarter Than You
GWT is Smarter Than YouGWT is Smarter Than You
GWT is Smarter Than You
Robert Cooper
 
Asp.net performance
Asp.net performanceAsp.net performance
Asp.net performance
Abhishek Sur
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
Andy Peterson
 
Enhance Web Performance
Enhance Web PerformanceEnhance Web Performance
Enhance Web Performance
Adam Lu
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular App
Katy Slemon
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
Ioan Eugen Stan
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
 
backend
backendbackend
backend
tutorialsruby
 
backend
backendbackend
backend
tutorialsruby
 

Similar to High Performance Ajax Applications 1197671494632682 2 (20)

Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
 
Silicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NET
Silicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NETSilicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NET
Silicon Valley CodeCamp 2008: High performance Ajax with ExtJS and ASP.NET
 
The Web on OSGi: Here's How
The Web on OSGi: Here's HowThe Web on OSGi: Here's How
The Web on OSGi: Here's How
 
My 70-480 HTML5 certification learning
My 70-480 HTML5 certification learningMy 70-480 HTML5 certification learning
My 70-480 HTML5 certification learning
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performance
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
From Zero to Hero – Web Performance
From Zero to Hero – Web PerformanceFrom Zero to Hero – Web Performance
From Zero to Hero – Web Performance
 
Developing High Performance Web Apps
Developing High Performance Web AppsDeveloping High Performance Web Apps
Developing High Performance Web Apps
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnitWriting and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
 
Front-end optimisation & jQuery Internals (Pycon)
Front-end optimisation & jQuery Internals (Pycon)Front-end optimisation & jQuery Internals (Pycon)
Front-end optimisation & jQuery Internals (Pycon)
 
GWT is Smarter Than You
GWT is Smarter Than YouGWT is Smarter Than You
GWT is Smarter Than You
 
Asp.net performance
Asp.net performanceAsp.net performance
Asp.net performance
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 
Enhance Web Performance
Enhance Web PerformanceEnhance Web Performance
Enhance Web Performance
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular App
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
backend
backendbackend
backend
 
backend
backendbackend
backend
 

Recently uploaded

20240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 202420240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 2024
Matthew Sinclair
 
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
Toru Tamaki
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
UiPathCommunity
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
Safe Software
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
Andrey Yasko
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
Password Rotation in 2024 is still Relevant
Password Rotation in 2024 is still RelevantPassword Rotation in 2024 is still Relevant
Password Rotation in 2024 is still Relevant
Bert Blevins
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
Kief Morris
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
Larry Smarr
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Erasmo Purificato
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
Stephanie Beckett
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
huseindihon
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
Yevgen Sysoyev
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
ishalveerrandhawa1
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
jackson110191
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
Liveplex
 
WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
Lidia A.
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
Mark Billinghurst
 
Manual | Product | Research Presentation
Manual | Product | Research PresentationManual | Product | Research Presentation
Manual | Product | Research Presentation
welrejdoall
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 

Recently uploaded (20)

20240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 202420240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 2024
 
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
Password Rotation in 2024 is still Relevant
Password Rotation in 2024 is still RelevantPassword Rotation in 2024 is still Relevant
Password Rotation in 2024 is still Relevant
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
 
WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
 
Manual | Product | Research Presentation
Manual | Product | Research PresentationManual | Product | Research Presentation
Manual | Product | Research Presentation
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 

High Performance Ajax Applications 1197671494632682 2

  • 1. High Performance Ajax Applications Julien Lecomte http://www.julienlecomte.net/blogfiles/performance/ajax-perf.ppt http://www.slideshare.net/julien.lecomte/high-performance-ajax-applications
  • 2. Part 1 Developing For High Performance
  • 3. Planning and designing for high performance Plan for performance from day 1 Work closely with designers and product managers Understand design rationale Explain the tradeoffs between design and performance Offer alternatives and show what is possible (prototype) Challenge yourself to implement challenging designs (don't just say no) Help simplify the design and interaction if needed (compromise)
  • 4. Engineering high performance: A few basic rules Less is more Don’t do anything unnecessary. Don’t do anything until it becomes absolutely necessary. Break the rules Make compromises and break best practices, but only as a last resort! Work on improving perceived performance Users can deal with some reasonable amount of slowness if: They are informed appropriately that an operation is pending. The user interface remains reactive at all time. Cheat whenever you can by first updating the UI and then do the work. Need to “lock” all or part of the user interface.
  • 5. Measuring performance Test performance using a setup similar to your users’ environment Profile your code during development Automate profiling/performance testing Keep historical records of how features perform Consider keeping some (small amount of) profiling code in production
  • 6. Part 2 High Performance Page Load
  • 7. Yahoo!'s Exceptional Performance rules Make Fewer HTTP Requests Use a Content Delivery Network Add an Expires Header Gzip Components (including JS!) Put CSS at the Top Move Scripts to the Bottom Avoid CSS Expressions Make JavaScript and CSS External Reduce DNS Lookups Minify JavaScript Avoid Redirects Remove Duplicate Scripts Configure ETags Make Ajax Cacheable See http://developer.yahoo.com/performance/ for more information. A web page works in 3 (sometimes imbricated) stages: load render run These rules cover mostly the first stage.
  • 8. Asset optimization Minify CSS and JavaScript files: Use the YUI Compressor [ http://developer.yahoo.com/yui/compressor/ ] Stay away from so-called advanced compression schemes - like Packer Combine CSS and JavaScript files: At build time [ http://www.julienlecomte.net/blog/2007/09/16/ ] At run time Optimize image assets: PngCrush [ http://pmt.sourceforge.net/pngcrush/ ] PngOptimizer [ http://psydk.org/PngOptimizer.php ] etc.
  • 9. Reduce unminified code size Loading and parsing HTML, CSS and JavaScript code is costly. Be concise and write less code. Make good use of JavaScript libraries. Consider splitting your large JavaScript files into smaller files (bundles) when the parsing and compilation of the script takes an excessive amount of time ( Firefox bug #313967 ) Load code (HTML, CSS and JavaScript) on demand (a.k.a “lazy loading”) See http://ajaxpatterns.org/On-Demand_Javascript Use the YUI Loader Dojo's package system JSAN Import System
  • 10. Optimize initial rendering (1/4) Miscellaneous tips... Consider rendering the first view on the server: Be aware of the added page weight You will still need to attach event handlers once the DOM is ready Close Your HTML Tags to Speed Up Parsing: Implicitly closed tags add cost to HTML parsing http://msdn2.microsoft.com/en-us/library/ms533020.aspx#Close_Your_Tags Consider flushing the apache buffer very early on: The download of external CSS files (should be at the top of the page!) may get a head start. May not influence the rendering speed however. Browsers buffer their input before displaying it. Load only essential assets / load assets on a delay or on demand Use the YUI Image Loader
  • 11. Optimize initial rendering (2/4) Don’t always wait for onload ... Most DOM operations can be accomplished before the onload event has fired. If you have control over where your code is going to be inserted in the page, write your init code in a <script> block located right before the closing </body> tag. Otherwise, use the YUI Event utility’s onDOMReady method: YAHOO.util.Event.onDOMReady( function () { // Do something here... // e.g., attach event handlers. });
  • 12. Optimize initial rendering (3/4) Post-load script loading A well designed site should be fully functional, even without JavaScript enabled. Therefore, you may be able to load scripts on a delay. Doing so benefits the loading of other assets (style sheets, images, etc.) Which makes your site load faster Right before the closing </body> tag, insert the following: <script> window.onload = function () { var script = document.createElement( &quot;script&quot; ); script.src = ...; document.body.appendChild(script); }; </script>
  • 13. Optimize initial rendering (4/4) Conditional preloading Preloading assets (JavaScript, CSS, Images, etc.) has the potential to really enhance the user experience. However, one must be smart about when the preloading takes place. Otherwise, the preloading may actually worsen the user experience... http://www.sitepoint.com/article/web-site-optimization-steps/3 Try it at http://search.yahoo.com/
  • 14. Part 3 High Performance JavaScript
  • 15. Reduce the amount of symbolic look-up: The scope chain (1/2) var g = 7 ; function f(a) { var v = 8 ; x = v + a + g; } f(6); parent Look-up is performed every time a variable is accessed. Variables are resolved backwards from most specific to least specific scope.
  • 16. Reduce the amount of symbolic look-up: The scope chain (2/2) Therefore, declare (with the var keyword) and use variables in the same scope whenever possible, and avoid global variables at all costs. Never use the with keyword, as it prevents the compiler from generating code for fast access to local variables (traverse the object prototype chain first, and then up the scope chain, and so on) Cache the result of expensive look-ups in local variables: var arr = ...; var globalVar = 0 ; ( function () { var i; for (i = 0 ; i < arr.length; i++) { globalVar++; } })(); var arr = ...; var globalVar = 0 ; ( function () { var i, l, localVar; l = arr.length; localVar = globalVar; for (i = 0 ; i < l; i++) { localVar++; } globalVar = localVar; })(); (faster on all A-grade browsers)
  • 17. Reduce the amount of symbolic look-up: The prototype chain function A () {} A.prototype.prop1 = ...; function B () { this .prop2 = ...; } B.prototype = new A(); var b = new B(); B.prototype Accessing members bound to the primary object is about 25% faster than accessing members defined anywhere in the prototype chain. The longer the traversal of the prototype chain, the slower the look-up.
  • 18. Optimize object instantiation If you need to create many objects, consider adding members to the prototype instead of adding them to each individual object in the object constructor (properties are bound once, to the prototype object) This also reduces memory consumption. However, it slows down the look-up of object members. function Foo () {...} Foo.prototype.bar = function () {...}; function Foo () { this .bar = function () {...}; }
  • 19. Don’t use eval ! The string passed to eval (and its relatives, the Function constructor and the setTimeout and setInterval functions) needs to be compiled and interpreted. Extremely slow! Never pass a string to the setTimeout and setInterval functions. Instead, pass an anonymous function like so: setTimeout( function () { // Code to execute on a timeout }, 50 ); Never use eval and the Function constructor (except in some extremely rare cases, and only in code blocks where performance is not critical)
  • 20. Optimize string concatenation On Internet Explorer (JScript), concatenating two strings causes a new string to be allocated, and the two original strings to be copied: var s = “xxx” + “yyy” ; s += “zzz” ; Therefore, it is much faster on Internet Explorer to append strings to an array, and then use Array.join (don’t use this for simple concatenations!) var i, s = “” ; for (i = 0 ; i < 10000 ; i++) { s += “x” ; } var i, s = []; for (i = 0 ; i < 10000 ; i++) { s[i] = “x” ; } s = s.join( “” ); Other JavaScript engines (WebKit, SpiderMonkey) have been optimized to handle string concatenations by doing a realloc + memcpy whenever possible. Use the YUI Compressor!
  • 21. Optimize regular expressions Don’t use the RegExp constructor, unless your regular expression is assembled at runtime. Instead, use regular expression literals. Use the test method if all you want to do is test for a pattern (the exec method carries a small performance penalty) Use non-capturing groups (?: ... ) Stick to simple patterns. If your regular expression looks like the following, reconsider... if ( /loaded|complete/ .test(document.readyState)) {...} (?:(?:)?[])*(?:(?:(?:[^()<>@,;:&quot;.00-31]+(?:(?:(?:)?[])+||(?=[&quot;()<>@,;:&quot;.]))|&quot; (?:[^amp;quot;]|.|(?:(?:)?[]))*&quot;(?:(?:)?[])*)(?:(?:(?:)?[])*(?:[^()<>@,;:&quot;.00-31 ]+(?:(?:(?:)?[])+||(?=[&quot;()<>@,;:&quot;.]))|&quot;(?:[^amp;quot;]|.|(?:(?:)?[]))*&quot;(?:(?:)?[]) *))*@(?:(?:)?[])*(?:[^()<>@,;:&quot;.00-31]+(?:(?:(?:)?[])+||(?=[&quot;()<>@,;:&quot;.]))| ([^]|.)*(?:(?:)?[])*)(?:(?:(?:)?[])*(?:[^()<>@,;:&quot;.00-31]+(?:(?:(?:)? [])+||(?=[&quot;()<>@,;:&quot;.]))|([^]|.)*(?:(?:)?[])*))*|(?:[^()<>@,;:&quot;.00- 31]+(?:(?:(?:)?[])+||(?=[&quot;()<>@,;:&quot;.]))|&quot;(?:[^amp;quot;]|.|(?:(?:)?[]))*&quot;(?:(?:)?[ ])*)*lt;(?:(?:)?[])*(?:@(?:[^()<>@,;:&quot;.00-31]+(?:(?:(?:)?[])+||(?=[&quot;()<>@,;:&quot;. ]))|([^]|.)*(?:(?:)?[])*)(?:(?:(?:)?[])*(?:[^()<>@,;:&quot;.00-31]+(?:(?:(?: )?[])+||(?=[&quot;()<>@,;:&quot;.]))|([^]|.)*(?:(?:)?[])*))*(?:,@(?:(?:)?[]))
  • 22. Caching Caching can be justified by: High cost (CPU or network latency) associated with getting a value Value will be read many times And will not change often! Increases memory consumption  tradeoff Memoization: var fn = ( function () { var b = false , v; return function () { if (!b) { v = ...; b = true ; } return v; }; })(); function fn () { if (!fn.b) { fn.v = ...; fn.b = true ; } return fn.v; } var fn = function () { var v = ...; return (fn = function () { return v; })(); }; Module pattern Store value in function object Lazy function definition
  • 23. How to handle long running JavaScript processes (1/2) During long running JavaScript processes, the entire browser UI is frozen Therefore, to maintain a decent user experience, make sure that JavaScript threads never take more than ~ 300 msec (at most) to complete. You can break long running processes into smaller units of work, and chain them using setTimeout . You can also process the data on the server. More info at http://www.julienlecomte.net/blog/2007/10/28 Demo
  • 24. How to handle long running JavaScript processes (2/2) function doSomething (callbackFn) { // Initialize a few things here... ( function () { // Do a little bit of work here... if ( termination condition ) { // We are done callbackFn(); } else { // Process next chunk setTimeout(arguments.callee, 0); } })(); }
  • 25. Miscellaneous tips (1/2) Primitive operations are often faster than the corresponding function calls: var a = 1 , b = 2 , c; c = Math.min(a, b); c = a < b ? a : b; If possible, avoid using try...catch in performance-critical sections: var i; for (i = 0 ; i < 100000 ; i++) { try { ... } catch (e) { ... } } var i; try { for (i = 0 ; i < 100000 ; i++) { ... } } catch (e) { ... } myArray.push(value); myArray[myArray.length] = value; myArray[idx++] = value;
  • 26. Miscellaneous tips (2/2) If possible, avoid for...in in performance-critical sections: var key, value; for (key in myArray) { value = myArray[key]; ... } var i, value, length = myArray.length; for (i = 0 ; i < length; i++) { value = myArray[i]; ... } Branch outside, not inside, whenever the branching condition does not change: function fn () { if (...) { ... } else { ... } } var fn; if (...) { fn = function () {...}; } else { fn = function () {...}; }
  • 27. Part 4 High Performance Dynamic HTML
  • 28. Document tree modification Using innerHTML var i, j, el, table, tbody, row, cell; el = document.createElement( &quot;div&quot; ); document.body.appendChild(el); table = document.createElement( &quot;table&quot; ); el.appendChild(table); tbody = document.createElement( &quot;tbody&quot; ); table.appendChild(tbody); for (i = 0 ; i < 1000 ; i++) { row = document.createElement( &quot;tr&quot; ); for (j = 0 ; j < 5 ; j++) { cell = document.createElement( &quot;td&quot; ); row.appendChild(cell); } tbody.appendChild(row); } var i, j, el, idx, html; idx = 0 ; html = []; html[idx++] = &quot;<table>&quot; ; for (i = 0 ; i < 1000 ; i++) { html[idx++] = &quot;<tr>&quot; ; for (j = 0 ; j < 5 ; j++) { html[idx++] = &quot;<td></td>&quot; ; } html[idx++] = &quot;</tr>&quot; ; } html[idx++] = &quot;</table>&quot; ; el = document.createElement( &quot;div&quot; ); document.body.appendChild(el); el.innerHTML = html.join( &quot;&quot; ); ( much faster on all A-grade browsers) Warning: See http://www.julienlecomte.net/blog/2007/12/38/
  • 29. Document tree modification Using cloneNode var i, j, el, table, tbody, row, cell; el = document.createElement( &quot;div&quot; ); document.body.appendChild(el); table = document.createElement( &quot;table&quot; ); el.appendChild(table); tbody = document.createElement( &quot;tbody&quot; ); table.appendChild(tbody); for (i = 0 ; i < 1000 ; i++) { row = document.createElement( &quot;tr&quot; ); for (j = 0 ; j < 5 ; j++) { cell = document.createElement( &quot;td&quot; ); row.appendChild(cell); } tbody.appendChild(row); } var i, el, table, tbody, template, row, cell; el = document.createElement( &quot;div&quot; ); document.body.appendChild(el); table = document.createElement( &quot;table&quot; ); el.appendChild(table); tbody = document.createElement( &quot;tbody&quot; ); table.appendChild(tbody); template = document.createElement( &quot;tr&quot; ); for (i = 0 ; i < 5 ; i++) { cell = document.createElement( &quot;td&quot; ); template.appendChild(cell); } for (i = 0 ; i < 1000 ; i++) { row = template.cloneNode(true); tbody.appendChild(row); } (faster on all A-grade browsers – sometimes much faster) Warning: expando properties/attached event handlers are lost!
  • 30. Document tree modification Using DocumentFragment A DocumentFragment (DOM Level 1 Core) is a lightweight Document object. It supports only a subset of the regular DOM methods and properties. IE’s implementation of the DocumentFragment interface does not comply with the W3C specification and returns a regular Document object. var i, j, el, table, tbody, row, cell, docFragment; docFragment = document.createDocumentFragment(); el = document.createElement( &quot;div&quot; ); docFragment.appendChild(el); table = document.createElement( &quot;table&quot; ); el.appendChild(table); tbody = document.createElement( &quot;tbody&quot; ); table.appendChild(tbody); for (i = 0 ; i < 1000 ; i++) { ... } document.body.appendChild(docFragment);
  • 31. Limit the number of event handlers (1/2) Attaching an event handler to hundreds of elements is very costly Multiplying event handlers augments the potential for memory leaks Solution: Use event delegation , a technique that relies on event bubbling <div id= &quot;container&quot; > <ul> <li id= &quot;li-1&quot; > List Item 1 </li> <li id= &quot;li-2&quot; > List Item 2 </li> <li id= &quot;li-3&quot; > List Item 3 </li> <li id= &quot;li-4&quot; > List Item 4 </li> <li id= &quot;li-5&quot; > List Item 5 </li> ... </ul> </div> div#container ul li#li- x text node
  • 32. Limit the number of event handlers (2/2) YAHOO.util.Event.addListener( &quot;container&quot; , &quot;click&quot; , function (e) { var el = YAHOO.util.Event.getTarget(e); while (el.id !== &quot;container&quot; ) { if (el.nodeName.toUpperCase() === &quot;LI&quot; ) { // Do something here... break; } else { el = el.parentNode; } } });
  • 33. Limiting reflows Reflows happen whenever the DOM tree is manipulated. Browsers have optimizations you may take advantage of to minimize reflow: Modifying an invisible element (display:none) does not trigger reflow Modifying an element “off-DOM” does not trigger reflow Batch style changes: Change the value of the style attribute using setAttribute (does not work on Internet Explorer) Example: Change the value of the cssText property of the style object. Example: More maintainable: Change the CSS class name of an element. Example: el.style.cssText = &quot;display:block;width:auto;height:100px;...&quot; ; YAHOO.util.Dom.replaceClass(el, &quot;foo&quot; , &quot;bar&quot; ); el.setAttribute( &quot;style&quot; , &quot;display:block;width:auto;height:100px;...&quot; );
  • 34. Miscellaneous tips... Consider using the onmousedown event instead of the onclick event Get a head start by making use of the small delay between the time a user presses the mouse button and the time he/she releases it. “ Downshift your code”: throttle frequent and expensive actions See http://yuiblog.com/blog/2007/07/09/downshift-your-code/
  • 35. Part 5 High Performance Layout and CSS
  • 36. Miscellaneous tips... Use CSS Sprites for Snappy Image Replacement. Avoid using JavaScript for layout. window.onresize is throttled... Use pure CSS instead! Side benefits: improves maintainability, degrades more gracefully, etc. Avoid using Internet Explorer expressions Expressions are constantly evaluated in order to react to environment changes. There are ways to more safely use expressions, but in general, you shouldn’t need/use them. Avoid using Internet Explorer filters (or keep their use to a minimum) Optimize Table Layout Goal: allow the rendering engine to start rendering a table before it has received all the data Use table-layout:fixed Explicitly define a COL element for each column Set the WIDTH attribute on each col Optimize your CSS selectors [ http://developer.mozilla.org/en/docs/Writing_Efficient_CSS ]
  • 37. Part 6 High Performance Ajax
  • 38. Ajax Best Practices Never resort to using synchronous XMLHttpRequest http://yuiblog.com/blog/2006/04/04/synchronous-v-asynchronous/ Asynchronous programming model slightly more complicated. Need to lock all or part of the UI while the transaction is pending. Programmatically handle network timeouts. Solution: Use the YUI Connection Manager: var callback = { success: function () { /* Do something */ }, failure: function () { /* Do something */ }, timeout: 5000 }; YAHOO.util.Connect.asyncRequest( &quot;GET&quot; , url, callback);
  • 39. Improving perceived network latency using the optimistic pattern If the data is validated locally (on the client, using JavaScript) before being sent to the server, the request will be successful in 99.9% of the cases. Therefore, in order to optimize the user experience, we should assume a successful outcome and adopt the following pattern: Update the UI when the request gets sent. Lock the UI/data structures with the finest possible granularity. Let the user know that something is happening. Let the user know why a UI object is locked. Unlock the UI/data structures when the outcome is successful. Handle error cases gracefully.
  • 40. Miscellaneous tips... Be aware of the maximum number of concurrent HTTP/1.1 connections. Multiplex Ajax requests whenever possible, and if your backend supports it. Piggyback unsollicited notifications in a response to an Ajax request. Favor JSON over XML as your data exchange format Accessing a JSON data structure is easier and cheaper than accessing XML data. JSON has less overhead than XML. Push, don’t poll. Use COMET to send real-time notifications to the browser. Consider using local storage to cache data locally, request a diff from the server: Internet Explorer’s userData Flash local storage DOM:Storage (WhatWG persistent storage API, implemented in Firefox 2) Google Gears etc.
  • 42. Performance Tools YSlow? [ http://developer.yahoo.com/yslow/ ] Task manager IE Leak Detector a.k.a Drip [ http://www.outofhanwell.com/ieleak/ ] Stopwatch profiling AjaxView [ http://research.microsoft.com/projects/ajaxview/ ] JsLex [ http://rockstarapps.com/pmwiki/pmwiki.php?n=JsLex.JsLex ] YUI profiler [ http://developer.yahoo.com/yui/profiler/ ] Venkman or Firebug Profiler [ http://www.getfirebug.com/ ]