Your SlideShare is downloading. ×
Fast Cordova applications
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.


Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

Fast Cordova applications


Published on

Slides of a talk of a seminars series I gave at WebRatio in January 2014. …

Slides of a talk of a seminars series I gave at WebRatio in January 2014.

I implemented many best practices and advices in this presentation in a generic app template available here:

Published in: Technology

  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. Fast Cordova applications Ivano Malavolta DISIM | University of L’Aquila
  • 2. Roadmap • • • • • • I implemented many best practices and advices in this presentation in a generic app template available here: Introduction Use the DOM efficiently Master events Be smart with the network Take advantage of CSS features Take care of memory issues
  • 3. Introduction You will leave this presentation with... understanding of what makes a Cordova app fast techniques to improve the performance of your Cordova apps In any case, step zero to success is to be technologically ready, for example many people tend to underestimate JavaScript, don't!
  • 4. Roadmap • • • • • • Introduction Use the DOM efficiently Master events Be smart with the network Take advantage of CSS features Take care of memory issues
  • 5. Always “cache” elements from the DOM every time you do $(‘id’) the browser must parse the whole DOM Don’t do this Do this
  • 6. Minimize DOM reflows Reflow: the browser process for calculating positions and geometries for HTML DOM elements A reflow is triggered every time the content of the DOM changes, DOM elements are resized, CSS positioning/padding/margins are changed, etc. • Use CSS transforms, transitions and animation • Use fixed widths and heights (when possible) • Avoid changing elements of the DOM They change the appearance of the DOM, but do not trigger a reflow op
  • 7. Keep your DOM slim Reflow operations are much heavier when • the number of nodes in the DOM is large • there are deeply nested DOM nodes Element Element Element Element Document HTML Body Element Element Element Element Element
  • 8. Navigate the DOM with built-in methods Avoid to continuously query the DOM if you can reach specific DOM nodes using its built-in methods Don’t do this Do this
  • 9. Examples of built-in JS properties for navigation element.parentNode — returns the node containing the element in the DOM element.childNodes; — returns all the nested nodes of the element in the DOM element.firstChild — retrieves the first nested node of the element in the DOM element.lastChild — retrieves the last nested node of the element in the DOM element.nextSibling — returns the node immediately following the element in the DOM element.previousSibling — returns the node immediately preceding the element in the DOM
  • 10. Avoid to interact with the DOM too often Every time you append a node in the DOM, a reflow operation is triggered Don’t do this Do this
  • 11. Prefer built-in JavaScript methods Under the lines, all the JS frameworks end up in calling standard JavaScript methods  when it’s possible, prefer JavaScript built-in methods to pass through a framework Don’t do this Don’t be tempted by the jQuery’s omni-present $("selector"), it is much more slower than JS built-in methods Do this Many frameworks contain a lot of workarounds and fallbacks for older browsers that we are not targeting (e.g., Internet Explorer 7)
  • 12. Examples of built-in JS methods element.innerHTML; — returns the contents of the DOM node element.innerHTML = " contents "; — appends contents to the DOM node element.hasAttribute(" attribute") — tests whether the DOM node has a specific attribute element.getAttribute(" attribute") — returns the value of a specific attribute element.setAttribute(" name", " value ") — adds a specific attribute to the DOM node element.removeAttribute(" attribute") —removes a specific attribute to the DOM node
  • 13. Examples of built-in JS methods domNode.innerHTML; — returns the contents of the DOM node domNode.innerHTML = " contents "; — appends contents to the DOM node domNode.parentNode.removeChild(domNode); — remove the node from the DOM element.classList.add() — adds a specific class to the DOM element.classList.remove() — adds a specific class to the DOM element.classList.toggle() — adds a specific class to the DOM ... and many more
  • 14. Try to avoid using Regular expressions When used frequently with large inputs a Regex can be a performance killer  when it’s possible, prefer HTML5 form validation attrib utes or String operations Don’t do this Do this
  • 15. Try to avoid using Regular expressions If the input is of a form input is knowna priori, use one of the following: • date • datetime • datetime-local • email • month • number • range • search • tel • time • url • week date tel • color number
  • 16. Roadmap • • • • • • Introduction Use the DOM efficiently Master events Be smart with the network Take advantage of CSS features Take care of memory issues
  • 17. Events Every time the user interacts with the DOM, a set of events is triggered in your JS application We can listen to these events by means of registered eventHandlers An eventHandler is a function automatically called by the browser, where data about the triggered event is available as a parameter Event handlers can be unregistered
  • 18. Events example name of the envet manage the event in the capture phase data about the event callback function
  • 19. Touch events Touch events are triggered when the user touches the display The event can describe one or more points of contact Touches are represented by the Touch object containing: • position • size and shape • amount of pressure • target element Lists of touches are represented by TouchList objects
  • 20. Touch events Main attributes of a touch event: TouchEvent.touches a TouchList of Touches TouchEvent.type the type of touch touchstart touchend touchmove touchenter touchcancel the element in the DOM TouchEvent.changedTouches a TouchList of all the Touches changed between this event and the previous one
  • 21. The Touch and TouchList objects relative to the whole display relative to the viewport
  • 22. Event default behaviour Each element in the DOM has a default behaviour ex. if you tap on an <a> element, it will make the browser to point to another location event.preventDefault(); Cancels the event if it is cancellable, without stopping further propagation of the event Usually, this is the last instruction of an event handler
  • 23. Capturing and bubbling When an event is triggered in the DOM, it can be: captured by all the elements containing the target element  event capturing captured first by the target and then BUBBLE up through all the HTML elements containing the target event bubbling
  • 24. Event delegation Delegation The act of establishing event handlers at higher levels in the DOM than the items of interest Don’t do this Do this WHY Using a lot of event handlers may lead to performance problems and they can be sources of memory leaks TIP Unbind event handlers as soon as possible so that they can be garbage collected
  • 25. Event throttling delay number of milliseconds function the function to be executed You get a new function, that when called repetitively, executes the original function no more than once every delay milliseconds. Given a specific delay, throttling limits the execution rate of the function • Useful when handling events with very high frequencies and whose execution rate must be limited ex. drag,scrolling, etc.
  • 26. Event debouncing delay number of milliseconds function the function to be executed You get a new function, that when called repetitively, executes the original function just once per “bunch” of calls, effectively coalescing multiple sequential calls into a single execution at either the beginning or end Given a specific delay, debouncing guarantees that the function will be executed only once • Useful when handling events with very high frequencies and that must be executed once ex. toggle state, Ajax request, etc.
  • 27. Throttling VS debouncing Throttling Debouncing Ben Alman’s famous implementations available here:
  • 28. Roadmap • • • • • • Introduction Use the DOM efficiently Master events Be smart with the network Take advantage of CSS features Take care of memory issues
  • 29. Network usage The network is the most umpredictable and memory consuming resource you have • Try to prefetch data as much as possible (possibly using Web Workers) • Bundle static data into the app • In any case, give visual feedback to the user when accessing the network
  • 30. Network usage • Be robust with respect to 404 errors, especially for images • Try to avoid synchronous network calls
  • 31. Web Workers Javascript is a single-threaded language  If a tasks take a lot of time, users have to wait Web Workers provide background processing capabilities to web applications They typically run on separate threads  apps can take advantage of multicore CPUs
  • 32. Web Workers Web Workers can be used to: • prefetch data from the Web • perform other ahead-of-time operations to provide a much more lively UI. Web Workers are precious on mobile applications because they usually need to load data over a potentially slow network
  • 33. Usage of web workers Any JS file can be launched as a worker Example of Web Worker declaration: In order to be independent from other workers, each worker script cannot access the DOM
  • 34. Usage of web workers The main thread and the worker can communicate via postMessage() calls and onmessage events send message to the worker response from the worker receive message respond
  • 35. Roadmap • • • • • • Introduction Use the DOM efficiently Master events Be smart with the network Take advantage of CSS features Take care of memory issues
  • 36. Rule of thumb If you can do something with CSS, do it! Corollaries: • Don’t use JavaScript for style-related operations • Don’t use images for something you can do with CSS CSS3 has many interesting features, like: • gradients • text manipulations & effects • the flex box • fonts • visual effects • media queries
  • 37. Gradients They can be used in every place you can use an image linear  the type of gradient (also radial, or repeating-linear) right-top  start of the gradient left-bottom  end of the gradient from  starting color to  final color
  • 38. Text manipulations text-align left | right center | justify text-transform none | capitalize | lowercase | uppercase Text-decoration none underline overline line through
  • 39. Text effects 2px  horizontal shadow 10px  vertical shadow 5px  blur distance #FF0000  color
  • 40. Other text properties
  • 41. The flex box It helps in styling elements to be arranged horizontally or vertically box: • a new value for the display property • a new property box-orient
  • 42. Flex Box main elements display: box opts an element and its immediate children into the flexible box model box-orient Values: horizontal | vertical | inherit how should the box's children be aligned? box-direction Values: normal | reverse | inherit sets the order in which the elements will be displayed
  • 43. Flex Box main elements box-pack Values: start | end | center | justify Sets the alignment of the box along the box-orient axis
  • 44. Flex Box main elements box-align Values: start | end | center | baseline | stretch Sets how the box's children are aligned in the box
  • 45. Flex box children By default child elements are not flexible  their dimension is set according to their width The box-flex property can be set to any integer, it sets how a child element occupy the box’s space
  • 46. Fonts Before CSS3, web designers had to use fonts that were already installed on the user's device With CSS3, web designers can use whatever font they like To use the font for an HTML element, refer to the font-family property font-weight normal bold 100 200 … font-style normal italic oblique
  • 47. Iconic fonts Iconic fonts contain ICONS instead of letters and symbols Advantages: • icons are now part of the CSS  you do not pollute the DOM with non-semantical elements • fonts are vector-based  you do not have to care anymore about the resolution of your icons • icon sets conform to the same style  you do not need to think about how your icons fit together
  • 48. Example of iconic font
  • 49. Visual effects Three main mechanisms: 1. Transforms (both 2D and 3D) 2. Transitions 3. Animations
  • 50. Transforms A transform is an effect that lets an element change shape, size, position, … You can transform your elements using 2D or 3D transformations
  • 51. Transforms
  • 52. Transforms
  • 53. Transitions They are used to add an effect when changing from one style to another The effect will start when the specified CSS property changes value Properties: property - the name of the CSS property the transition effect is for (can be all) duration - how many seconds (or milliseconds) the transition effect takes to complete timing-function - linear, ease, ease-in, ease-out, ease-in-out delay- when the transition effect will start
  • 54. Transition example
  • 55. Animations An animation is an effect that lets an element gradually change from one style to another You can change style in loop, repeating, etc. To bind an animation to an element, you have to specify at least: 1. Name of the animation 2. Duration of the animation
  • 56. Animations An animation is defined in a keyframe It splits the animation into parts, and assign a specific style to each part The various steps within an animation are given as percentuals 0%  beginning of the animation (from) 100%  end of the animation (to)
  • 57. Example of animation result in
  • 58. Animation properties
  • 59. Transition VS animation Trigger Transitions must be bound to a CSS property change Animations start autonomously States Transitions have start and end states Animations can have multiple states Repeats Transitions can be perfomed once for each activation Animations can be looped
  • 60. Media types Media Queries are based on Media Types A media type is a specification of the actual media that is being used to access the page Examples of media types include • screen: computer screens • print: printed document • braille: for Braille-based devices • tv: for television devices
  • 61. Media types There are two main ways to specify a media type: • <link> in the HTML page • @media within the CSS file
  • 62. Media queries They allow you to to change style based on specific conditions For example, they can be about • device’s display size • orientation of the device • resolution of the display • ...
  • 63. Media queries A media query is a boolean expression The CSS associated with the media query expression is applied only if it evaluates to true A media query consists of 1. a media type 2. a set of media features @media screen and orientation: portrait
  • 64. The full media feature list
  • 65. Operators AND to combine multiple expressions COMMA it acts as an OR operator NOT to explicitly ignore a specific type of device ONLY to “hide” the CSS to older browsers that can read media types but cannot handle media queries In this case the styling information will not be visible to those browsers
  • 66. Examples Retina Displays iPad in landscape orientation iPhone and Android devices
  • 67. Roadmap • • • • • • Introduction Use the DOM efficiently Master events Be smart with the network Take advantage of CSS features Take care of memory issues
  • 68. Take care of memory issues Wait, why should I worry if JavaScript has a garbage collector that automatically cleans my memory? True, it automatically cleans up and deallocates memory, but it must be sure about what it is deleting forever  you have to make it clear what code you are no longer using Definition of memoryleak A memory leak is the situation in which the available memory of your app gets gradually lost. In JavaScript a memory leak can happen when an object is stored in memory but cannot be accessed by the running code
  • 69. The retaining tree The garbage collector cleans up he portions of tree isolated from the root node In our apps the window object is the root of the tree
  • 70. Rules of thumb Use appropriate scope Better than de-referencing, use local scopes The key is to always have an healthy retaining tree Unbind event listeners Unbind events that are no longer needed, specially if the related DOM objects are going to be removed Manage local cache Be careful with storing large chunks of data that you are not going to use
  • 71. How to detect a memory leak 1. Open the Memory View in the Timeline tab 2. start recording 3. execute the suspicious actions 4. during the execution force a GC different times 5. If you see a sawtooth-shaped wave  no relevant memory leaks  You have a memory leak if one of the following do not drop down: used memory – number of DOM nodes – number of event handlers
  • 72. Examples of pattern No memory leak Memory leak detected It’s normal that during the investigation your memory grows, nothing is free! You have to pay for what you are doing in your app
  • 73. How to detect the source of your memory leak 1. Open the Heap Profile 2. Take a heap snapshot 3. Perform suspicious actions 4. Take a heap snapshot 5. Perform suspicious actions again 6. Take a final heap snapshot 7. Select the most recent snapshot taken 8. find the drop-down that says "All objects" and switch this to "Objects allocated between snapshots 1 and 2". (You can also do the same for 2 and 3 if needed) There, you will find the objects which have not been collected during the snapshots. It works because when you take a heap snapshot, Chrome forces also a GC execution.
  • 74. How to detect the source of your memory leak Now, start from the first object and check which references it is holding Shallow size the size of the object Retain size Detached DOM tree is a subtree of the DOM that 1) has been removed from the DOM, and 2) cannot be GCed because some JS objects is still referencing it the size of memory that can be freed once an object is deleted Yellow DOM nodes some JS object is referencing them Red DOM nodes Detached DOM trees, no JS object is referencing them, but they are alive
  • 75. Example #leaf maintains a reference to it's parent (parentNode) and recursively up to #tree, so only when leafRef is nullified is the WHOLE tree under #tree a candidate for GC.
  • 76. References
  • 77. Contact Ivano Malavolta | DISIM + 39 380 70 21 600 iivanoo