fast cordova applications

77
DISIM | University of L’Aquila Ivano Malavolta Fast Cordova applications

Upload: ivano-malavolta

Post on 07-May-2015

10.027 views

Category:

Technology


4 download

DESCRIPTION

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

TRANSCRIPT

Page 1: Fast Cordova applications

DISIM | University of L’Aquila

Ivano Malavolta

Fast Cordova applications

Page 2: Fast Cordova applications

Roadmap

• Introduction

• Use the DOM efficiently

• Master events

• Be smart with the network

• Take advantage of CSS features

• Take care of memory issues

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

https://github.com/iivanoo/cordovaboilerplate

Page 3: Fast Cordova applications

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

Page 4: Fast Cordova applications

Roadmap

• Introduction

• Use the DOM efficiently

• Master events

• Be smart with the network

• Take advantage of CSS features

• Take care of memory issues

Page 5: Fast Cordova applications

Always “cache” elements from the DOM

every time you do $(‘id’) the browser must parse the whole DOM

Don’t do this

Do this

Page 6: Fast Cordova applications

Minimize DOM reflows

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

Reflow: the browser process for calculating positions and geometries for HTML DOM elements

Page 7: Fast Cordova applications

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

Document HTML Body

Element

Element

Element

Element

Element

Element

Element

Element

Element

Page 8: Fast Cordova applications

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

Page 9: Fast Cordova applications

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

Page 10: Fast Cordova applications

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

Page 11: Fast Cordova applications

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

Do this

Don’t be tempted by the jQuery’s omni-present $("selector"), it is much more slower than JS built-in methods

Many frameworks contain a lot of workarounds and fallbacks for older browsers that we are not targeting (e.g., Internet Explorer 7)

Page 12: Fast Cordova applications

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

Page 13: Fast Cordova applications

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

Page 14: Fast Cordova applications

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

Page 15: Fast Cordova applications

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 • color

http://mobiforge.com/design-development/html5-mobile-web-forms-and-input-types

date tel number

Page 16: Fast Cordova applications

Roadmap

• Introduction

• Use the DOM efficiently

• Master events

• Be smart with the network

• Take advantage of CSS features

• Take care of memory issues

Page 17: Fast Cordova applications

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

Page 18: Fast Cordova applications

Events example

name of the envet

callback function

manage the event in the capture phase

data about the event

Page 19: Fast Cordova applications

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

Page 20: Fast Cordova applications

Touch events

Main attributes of a touch event:

TouchEvent.touches

a TouchList of Touches

TouchEvent.type

the type of touch

TouchEvent.target

the element in the DOM

TouchEvent.changedTouches

a TouchList of all the Touches changed between this event and the previous one

touchstart touchend touchmove touchenter touchcancel

Page 21: Fast Cordova applications

The Touch and TouchList objects

relative to the whole display

relative to the viewport

Page 22: Fast Cordova applications

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

Page 23: Fast Cordova applications

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

Page 24: Fast Cordova applications

Event delegation

Don’t do this

Do this

Delegation The act of establishing event handlers at higher levels in the DOM than the items of interest

TIP Unbind event handlers as soon as possible so that they can be garbage collected

WHY Using a lot of event handlers may lead to performance problems and they can be sources of memory leaks

Page 25: Fast Cordova applications

Event throttling

delay

number of milliseconds

function

the function to be executed

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.

You get a new function, that when called repetitively, executes the original function no more than once every delay milliseconds.

Page 26: Fast Cordova applications

Event debouncing

delay

number of milliseconds

function

the function to be executed

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.

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

Page 27: Fast Cordova applications

Throttling VS debouncing

Throttling

Debouncing

Ben Alman’s famous implementations available here: http://benalman.com/projects/jquery-throttle-debounce-plugin/

Page 28: Fast Cordova applications

Roadmap

• Introduction

• Use the DOM efficiently

• Master events

• Be smart with the network

• Take advantage of CSS features

• Take care of memory issues

Page 29: Fast Cordova applications

Network usage

• 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

The network is the most umpredictable and memory consuming resource you have

http://fgnass.github.io/spin.js

Page 30: Fast Cordova applications

Network usage

• Be robust with respect to 404 errors, especially for images

• Try to avoid synchronous network calls

Page 31: Fast Cordova applications

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

Page 32: Fast Cordova applications

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

Page 33: Fast Cordova applications

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

Page 34: Fast Cordova applications

Usage of web workers

The main thread and the worker can communicate via postMessage() calls and onmessage events

send message to the worker respond receive message response from the worker

Page 35: Fast Cordova applications

Roadmap

• Introduction

• Use the DOM efficiently

• Master events

• Be smart with the network

• Take advantage of CSS features

• Take care of memory issues

Page 36: Fast Cordova applications

Rule of thumb

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

If you can do something with CSS, do it!

Page 37: Fast Cordova applications

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

Page 38: Fast Cordova applications

Text manipulations

text-transform none | capitalize |

lowercase | uppercase

text-align left | right

center | justify

Text-decoration none

underline overline

line through

Page 39: Fast Cordova applications

Text effects

2px horizontal shadow

10px vertical shadow

5px blur distance

#FF0000 color

Page 40: Fast Cordova applications

Other text properties

Page 41: Fast Cordova applications

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

Page 42: Fast Cordova applications

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

Page 43: Fast Cordova applications

Flex Box main elements

box-pack

Values: start | end | center | justify

Sets the alignment of the box along the box-orient axis

Page 44: Fast Cordova applications

Flex Box main elements

box-align

Values: start | end | center | baseline | stretch

Sets how the box's children are aligned in the box

Page 45: Fast Cordova applications

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

Page 46: Fast Cordova applications

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-style normal

italic oblique

font-weight normal

bold 100 200

Page 47: Fast Cordova applications

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

Page 48: Fast Cordova applications

Example of iconic font http://typicons.com

Page 49: Fast Cordova applications

Visual effects

Three main mechanisms:

1. Transforms (both 2D and 3D)

2. Transitions

3. Animations

Page 50: Fast Cordova applications

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

Page 51: Fast Cordova applications

Transforms

http://bit.ly/IrpUnX

Page 52: Fast Cordova applications

Transforms

http://bit.ly/IrpUnX

Page 53: Fast Cordova applications

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

Page 54: Fast Cordova applications

Transition example

Page 55: Fast Cordova applications

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

Page 56: Fast Cordova applications

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)

Page 57: Fast Cordova applications

Example of animation

result in http://goo.gl/ejp4Fy

Page 58: Fast Cordova applications

Animation properties

http://bit.ly/IrpUnX

Page 59: Fast Cordova applications

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

Page 60: Fast Cordova applications

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

Page 61: Fast Cordova applications

Media types

There are two main ways to specify a media type:

• <link> in the HTML page

• @media within the CSS file

Page 62: Fast Cordova applications

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

Page 63: Fast Cordova applications

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

Page 64: Fast Cordova applications

The full media feature list

http://slidesha.re/I5oFHZ

Page 65: Fast Cordova applications

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

Page 66: Fast Cordova applications

Examples

Retina Displays iPad in landscape orientation iPhone and Android devices

Page 67: Fast Cordova applications

Roadmap

• Introduction

• Use the DOM efficiently

• Master events

• Be smart with the network

• Take advantage of CSS features

• Take care of memory issues

Page 68: Fast Cordova applications

Take care of memory issues

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

Wait, why should I worry if JavaScript has a garbage collector that automatically cleans my memory?

Page 69: Fast Cordova applications

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

Page 70: Fast Cordova applications

Rules of thumb

Better than de-referencing, use local scopes Unbind events that are no longer needed, specially if the related DOM objects are going to be removed Be careful with storing large chunks of data that you are not going to use

Use appropriate scope

Unbind event listeners

Manage local cache

http://slid.es/gruizdevilla/memory

The key is to always have an healthy retaining tree

Page 71: Fast Cordova applications

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

Page 72: Fast Cordova applications

Examples of pattern http://goo.gl/UAZQvl

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

Page 73: Fast Cordova applications

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)

http://goo.gl/UAZQvl

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.

Page 74: Fast Cordova applications

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

the size of memory that can be freed once an object is deleted

Yellow DOM nodes

Red DOM nodes Detached DOM trees, no JS object is referencing them, but they are alive

some JS object is referencing them

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

Page 75: Fast Cordova applications

Example http://goo.gl/UAZQvl

#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.

Page 76: Fast Cordova applications

References

https://developer.mozilla.org/en-US/docs/JavaScript/Guide

https://github.com/iivanoo/cordovaboilerplate

Page 77: Fast Cordova applications

+ 39 380 70 21 600 Contact Ivano Malavolta | DISIM

iivanoo

[email protected]

www.ivanomalavolta.com