Fast Cordova applications
Upcoming SlideShare
Loading in...5
×
 

Fast Cordova applications

on

  • 4,877 views

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: https://github.com/iivanoo/cordovaboilerplate

Statistics

Views

Total Views
4,877
Views on SlideShare
3,435
Embed Views
1,442

Actions

Likes
7
Downloads
83
Comments
0

12 Embeds 1,442

http://www.modeldrivenstar.org 1099
http://www.ivanomalavolta.com 301
http://feeds.feedburner.com 16
http://plus.url.google.com 9
http://feedly.com 7
http://digg.com 2
http://translate.googleusercontent.com 2
http://webcache.googleusercontent.com 2
http://marcobrambi.blogspot.com 1
http://www.todayspecialoffers.com 1
http://www.directrss.co.il 1
http://www.tuicool.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

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

    Fast Cordova applications Fast Cordova applications Presentation Transcript

    • Fast Cordova applications Ivano Malavolta DISIM | University of L’Aquila
    • 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 https://github.com/iivanoo/cordovaboilerplate
    • 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! http://eloquentjavascript.net
    • Roadmap • • • • • • Introduction Use the DOM efficiently Master events Be smart with the network Take advantage of CSS features Take care of memory issues
    • Always “cache” elements from the DOM every time you do $(‘id’) the browser must parse the whole DOM Don’t do this Do this
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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)
    • 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
    • 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
    • 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
    • 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 http://mobiforge.com/design-development/html5-mobile-web-forms-and-input-types number
    • Roadmap • • • • • • Introduction Use the DOM efficiently Master events Be smart with the network Take advantage of CSS features Take care of memory issues
    • 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
    • Events example name of the envet manage the event in the capture phase data about the event callback function
    • 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
    • Touch events Main attributes of a touch event: TouchEvent.touches a TouchList of Touches TouchEvent.type the type of touch TouchEvent.target 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
    • The Touch and TouchList objects relative to the whole display relative to the viewport
    • 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
    • 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
    • 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
    • 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.
    • 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.
    • Throttling VS debouncing Throttling Debouncing Ben Alman’s famous implementations available here: http://benalman.com/projects/jquery-throttle-debounce-plugin/
    • Roadmap • • • • • • Introduction Use the DOM efficiently Master events Be smart with the network Take advantage of CSS features Take care of memory issues
    • 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 http://fgnass.github.io/spin.js
    • Network usage • Be robust with respect to 404 errors, especially for images • Try to avoid synchronous network calls
    • 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
    • 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
    • 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
    • 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
    • Roadmap • • • • • • Introduction Use the DOM efficiently Master events Be smart with the network Take advantage of CSS features Take care of memory issues
    • 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
    • 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
    • Text manipulations text-align left | right center | justify text-transform none | capitalize | lowercase | uppercase Text-decoration none underline overline line through
    • Text effects 2px  horizontal shadow 10px  vertical shadow 5px  blur distance #FF0000  color
    • Other text properties
    • 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
    • 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
    • Flex Box main elements box-pack Values: start | end | center | justify Sets the alignment of the box along the box-orient axis
    • Flex Box main elements box-align Values: start | end | center | baseline | stretch Sets how the box's children are aligned in the box
    • 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
    • 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
    • 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
    • Example of iconic font http://typicons.com
    • Visual effects Three main mechanisms: 1. Transforms (both 2D and 3D) 2. Transitions 3. Animations
    • Transforms A transform is an effect that lets an element change shape, size, position, … You can transform your elements using 2D or 3D transformations http://bit.ly/IroJ7S
    • Transforms http://bit.ly/IrpUnX
    • Transforms http://bit.ly/IrpUnX
    • 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
    • Transition example
    • 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
    • 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)
    • Example of animation result in http://goo.gl/ejp4Fy
    • Animation properties http://bit.ly/IrpUnX
    • 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
    • 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
    • Media types There are two main ways to specify a media type: • <link> in the HTML page • @media within the CSS file
    • 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 • ... http://bit.ly/I5mR1u
    • 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
    • The full media feature list http://slidesha.re/I5oFHZ
    • 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
    • Examples Retina Displays iPad in landscape orientation iPhone and Android devices
    • Roadmap • • • • • • Introduction Use the DOM efficiently Master events Be smart with the network Take advantage of CSS features Take care of memory issues
    • 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
    • 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 https://developers.google.com/chrome-developer-tools/docs/javascript-memory-profiling
    • 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 http://slid.es/gruizdevilla/memory
    • http://goo.gl/UAZQvl 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
    • http://goo.gl/UAZQvl 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
    • http://goo.gl/UAZQvl 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.
    • 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
    • http://goo.gl/UAZQvl 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.
    • References https://developer.mozilla.org/en-US/docs/JavaScript/Guide https://github.com/iivanoo/cordovaboilerplate
    • Contact Ivano Malavolta | DISIM + 39 380 70 21 600 iivanoo ivano.malavolta@univaq.it www.ivanomalavolta.com