SlideShare a Scribd company logo
1 of 77
Download to read offline
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

More Related Content

What's hot

Presentation wpf
Presentation wpfPresentation wpf
Presentation wpf
danishrafiq
 
Usability in the GeoWeb
Usability in the GeoWebUsability in the GeoWeb
Usability in the GeoWeb
Dave Bouwman
 
Ajax basics
Ajax basicsAjax basics
Ajax basics
Vel004
 
Engineering Concurrent and Event-driven Web Apps: an Agent-Oriented Approach ...
Engineering Concurrent and Event-driven Web Apps: an Agent-Oriented Approach ...Engineering Concurrent and Event-driven Web Apps: an Agent-Oriented Approach ...
Engineering Concurrent and Event-driven Web Apps: an Agent-Oriented Approach ...
Francesco Fabbri
 
Testing Single Page Webapp
Testing Single Page WebappTesting Single Page Webapp
Testing Single Page Webapp
Akshay Mathur
 

What's hot (20)

An Introduction to the Model-View-Controller Pattern
An Introduction to the Model-View-Controller PatternAn Introduction to the Model-View-Controller Pattern
An Introduction to the Model-View-Controller Pattern
 
Workshop HTML5+PhoneGap by Ivano Malavolta
Workshop HTML5+PhoneGap by Ivano Malavolta Workshop HTML5+PhoneGap by Ivano Malavolta
Workshop HTML5+PhoneGap by Ivano Malavolta
 
HTML5: the new frontier of the web
HTML5: the new frontier of the webHTML5: the new frontier of the web
HTML5: the new frontier of the web
 
Developing Series 40 web apps with Nokia Web Tools 2.0
Developing Series 40 web apps with Nokia Web Tools 2.0Developing Series 40 web apps with Nokia Web Tools 2.0
Developing Series 40 web apps with Nokia Web Tools 2.0
 
Presentation wpf
Presentation wpfPresentation wpf
Presentation wpf
 
[2015/2016] User experience design of mobil apps
[2015/2016] User experience design of mobil apps[2015/2016] User experience design of mobil apps
[2015/2016] User experience design of mobil apps
 
Modern development paradigms
Modern development paradigmsModern development paradigms
Modern development paradigms
 
Usability in the GeoWeb
Usability in the GeoWebUsability in the GeoWeb
Usability in the GeoWeb
 
2 Day - WPF Training by Adil Mughal
2 Day - WPF Training by Adil Mughal2 Day - WPF Training by Adil Mughal
2 Day - WPF Training by Adil Mughal
 
Optimizing Browser Rendering
Optimizing Browser RenderingOptimizing Browser Rendering
Optimizing Browser Rendering
 
Clean architecture with ddd layering in php
Clean architecture with ddd layering in phpClean architecture with ddd layering in php
Clean architecture with ddd layering in php
 
Ajax technology
Ajax technologyAjax technology
Ajax technology
 
Ajax basics
Ajax basicsAjax basics
Ajax basics
 
iOS Design Patterns
iOS Design PatternsiOS Design Patterns
iOS Design Patterns
 
Building Rich User Experiences Without JavaScript Spaghetti
Building Rich User Experiences Without JavaScript SpaghettiBuilding Rich User Experiences Without JavaScript Spaghetti
Building Rich User Experiences Without JavaScript Spaghetti
 
Engineering Concurrent and Event-driven Web Apps: an Agent-Oriented Approach ...
Engineering Concurrent and Event-driven Web Apps: an Agent-Oriented Approach ...Engineering Concurrent and Event-driven Web Apps: an Agent-Oriented Approach ...
Engineering Concurrent and Event-driven Web Apps: an Agent-Oriented Approach ...
 
DODN2009 - Jump Start Silverlight
DODN2009 - Jump Start SilverlightDODN2009 - Jump Start Silverlight
DODN2009 - Jump Start Silverlight
 
Design Patterns in iOS
Design Patterns in iOSDesign Patterns in iOS
Design Patterns in iOS
 
Moving from AS3 to Flex - advantages, hazards, traps
Moving from AS3 to Flex - advantages, hazards, trapsMoving from AS3 to Flex - advantages, hazards, traps
Moving from AS3 to Flex - advantages, hazards, traps
 
Testing Single Page Webapp
Testing Single Page WebappTesting Single Page Webapp
Testing Single Page Webapp
 

Viewers also liked

10 Most Surprising Hybrid Apps
10 Most Surprising Hybrid Apps10 Most Surprising Hybrid Apps
10 Most Surprising Hybrid Apps
Moovweb
 
Pasos para eliminar el virus conficker
Pasos para eliminar el virus confickerPasos para eliminar el virus conficker
Pasos para eliminar el virus conficker
Miriam Estrada
 
Creating Mobile Apps With PHP & Symfony2
Creating Mobile Apps With PHP & Symfony2Creating Mobile Apps With PHP & Symfony2
Creating Mobile Apps With PHP & Symfony2
Pablo Godel
 

Viewers also liked (14)

High Performance PhoneGap Apps
High Performance PhoneGap AppsHigh Performance PhoneGap Apps
High Performance PhoneGap Apps
 
10 Most Surprising Hybrid Apps
10 Most Surprising Hybrid Apps10 Most Surprising Hybrid Apps
10 Most Surprising Hybrid Apps
 
These mobile apps will let you totally rethink hybrid app development
These mobile apps will let you totally rethink hybrid app developmentThese mobile apps will let you totally rethink hybrid app development
These mobile apps will let you totally rethink hybrid app development
 
Performance Optimization for Sencha Touch
Performance Optimization for Sencha TouchPerformance Optimization for Sencha Touch
Performance Optimization for Sencha Touch
 
Loading native plugins using PhoneGap content-sync
Loading native plugins using PhoneGap content-syncLoading native plugins using PhoneGap content-sync
Loading native plugins using PhoneGap content-sync
 
Pasos para eliminar el virus conficker
Pasos para eliminar el virus confickerPasos para eliminar el virus conficker
Pasos para eliminar el virus conficker
 
Using The EGit Eclipse Plugin With Git Hub
Using The EGit Eclipse Plugin With Git HubUsing The EGit Eclipse Plugin With Git Hub
Using The EGit Eclipse Plugin With Git Hub
 
Finding the sweet spot - blending the best of native and web
Finding the sweet spot - blending the best of native and webFinding the sweet spot - blending the best of native and web
Finding the sweet spot - blending the best of native and web
 
Phonegap Day 2016: Ember/JS & Hybrid Apps Tips
Phonegap Day 2016: Ember/JS & Hybrid Apps TipsPhonegap Day 2016: Ember/JS & Hybrid Apps Tips
Phonegap Day 2016: Ember/JS & Hybrid Apps Tips
 
Securing Data in MongoDB with Gazzang and Chef
Securing Data in MongoDB with Gazzang and ChefSecuring Data in MongoDB with Gazzang and Chef
Securing Data in MongoDB with Gazzang and Chef
 
Developing a Modern Mobile App Strategy
Developing a Modern Mobile App StrategyDeveloping a Modern Mobile App Strategy
Developing a Modern Mobile App Strategy
 
The Graph Traversal Programming Pattern
The Graph Traversal Programming PatternThe Graph Traversal Programming Pattern
The Graph Traversal Programming Pattern
 
Creating Mobile Apps With PHP & Symfony2
Creating Mobile Apps With PHP & Symfony2Creating Mobile Apps With PHP & Symfony2
Creating Mobile Apps With PHP & Symfony2
 
Introduction to SEO
Introduction to SEOIntroduction to SEO
Introduction to SEO
 

Similar to Fast Cordova applications

Front-end optimisation & jQuery Internals
Front-end optimisation & jQuery InternalsFront-end optimisation & jQuery Internals
Front-end optimisation & jQuery Internals
Artur Cistov
 
Make Mobile Apps Quickly
Make Mobile Apps QuicklyMake Mobile Apps Quickly
Make Mobile Apps Quickly
Gil Irizarry
 
MvvmCross Introduction
MvvmCross IntroductionMvvmCross Introduction
MvvmCross Introduction
Stuart Lodge
 

Similar to Fast Cordova applications (20)

Speeding up mobile web apps
Speeding up mobile web appsSpeeding up mobile web apps
Speeding up mobile web apps
 
All about that reactive ui
All about that reactive uiAll about that reactive ui
All about that reactive ui
 
Front-end optimisation & jQuery Internals
Front-end optimisation & jQuery InternalsFront-end optimisation & jQuery Internals
Front-end optimisation & jQuery Internals
 
JavaScript and BOM events
JavaScript and BOM eventsJavaScript and BOM events
JavaScript and BOM events
 
Web Components
Web ComponentsWeb Components
Web Components
 
Real time web
Real time webReal time web
Real time web
 
Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014
Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014
Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014
 
orcreatehappyusers
orcreatehappyusersorcreatehappyusers
orcreatehappyusers
 
orcreatehappyusers
orcreatehappyusersorcreatehappyusers
orcreatehappyusers
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.js
 
Building high performance web apps.
Building high performance web apps.Building high performance web apps.
Building high performance web apps.
 
SWTT 140407 session04
SWTT 140407 session04SWTT 140407 session04
SWTT 140407 session04
 
Business of Front-end Web Development
Business of Front-end Web DevelopmentBusiness of Front-end Web Development
Business of Front-end Web Development
 
Make Mobile Apps Quickly
Make Mobile Apps QuicklyMake Mobile Apps Quickly
Make Mobile Apps Quickly
 
DevOops Redux Ken Johnson Chris Gates - AppSec USA 2016
DevOops Redux Ken Johnson Chris Gates  - AppSec USA 2016DevOops Redux Ken Johnson Chris Gates  - AppSec USA 2016
DevOops Redux Ken Johnson Chris Gates - AppSec USA 2016
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performance
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
 
MvvmCross Introduction
MvvmCross IntroductionMvvmCross Introduction
MvvmCross Introduction
 
MvvmCross Seminar
MvvmCross SeminarMvvmCross Seminar
MvvmCross Seminar
 

More from Ivano Malavolta

More from Ivano Malavolta (20)

Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
 
The H2020 experience
The H2020 experienceThe H2020 experience
The H2020 experience
 
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)
The Green Lab - Research cocktail  @Vrije Universiteit Amsterdam (October 2020)The Green Lab - Research cocktail  @Vrije Universiteit Amsterdam (October 2020)
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)
 
Software sustainability and Green IT
Software sustainability and Green ITSoftware sustainability and Green IT
Software sustainability and Green IT
 
Navigation-aware and Personalized Prefetching of Network Requests in Android ...
Navigation-aware and Personalized Prefetching of Network Requests in Android ...Navigation-aware and Personalized Prefetching of Network Requests in Android ...
Navigation-aware and Personalized Prefetching of Network Requests in Android ...
 
How Maintainability Issues of Android Apps Evolve [ICSME 2018]
How Maintainability Issues of Android Apps Evolve [ICSME 2018]How Maintainability Issues of Android Apps Evolve [ICSME 2018]
How Maintainability Issues of Android Apps Evolve [ICSME 2018]
 
Collaborative Model-Driven Software Engineering: a Classification Framework a...
Collaborative Model-Driven Software Engineering: a Classification Framework a...Collaborative Model-Driven Software Engineering: a Classification Framework a...
Collaborative Model-Driven Software Engineering: a Classification Framework a...
 
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
 
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
 
Modeling behaviour via UML state machines [Software Design] [Computer Science...
Modeling behaviour via UML state machines [Software Design] [Computer Science...Modeling behaviour via UML state machines [Software Design] [Computer Science...
Modeling behaviour via UML state machines [Software Design] [Computer Science...
 
Object-oriented design patterns in UML [Software Design] [Computer Science] [...
Object-oriented design patterns in UML [Software Design] [Computer Science] [...Object-oriented design patterns in UML [Software Design] [Computer Science] [...
Object-oriented design patterns in UML [Software Design] [Computer Science] [...
 
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
 
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
 
Modeling and abstraction, software development process [Software Design] [Com...
Modeling and abstraction, software development process [Software Design] [Com...Modeling and abstraction, software development process [Software Design] [Com...
Modeling and abstraction, software development process [Software Design] [Com...
 
[2017/2018] Agile development
[2017/2018] Agile development[2017/2018] Agile development
[2017/2018] Agile development
 
Reconstructing microservice-based architectures
Reconstructing microservice-based architecturesReconstructing microservice-based architectures
Reconstructing microservice-based architectures
 
[2017/2018] AADL - Architecture Analysis and Design Language
[2017/2018] AADL - Architecture Analysis and Design Language[2017/2018] AADL - Architecture Analysis and Design Language
[2017/2018] AADL - Architecture Analysis and Design Language
 
[2017/2018] Architectural languages
[2017/2018] Architectural languages[2017/2018] Architectural languages
[2017/2018] Architectural languages
 
[2017/2018] Introduction to Software Architecture
[2017/2018] Introduction to Software Architecture[2017/2018] Introduction to Software Architecture
[2017/2018] Introduction to Software Architecture
 
[2017/2018] RESEARCH in software engineering
[2017/2018] RESEARCH in software engineering[2017/2018] RESEARCH in software engineering
[2017/2018] RESEARCH in software engineering
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Recently uploaded (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Fast Cordova applications

  • 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 https://github.com/iivanoo/cordovaboilerplate
  • 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! http://eloquentjavascript.net
  • 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 http://mobiforge.com/design-development/html5-mobile-web-forms-and-input-types 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 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
  • 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: http://benalman.com/projects/jquery-throttle-debounce-plugin/
  • 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 http://fgnass.github.io/spin.js
  • 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
  • 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 http://typicons.com
  • 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 http://bit.ly/IroJ7S
  • 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
  • 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 http://goo.gl/ejp4Fy
  • 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 • ... http://bit.ly/I5mR1u
  • 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 http://slidesha.re/I5oFHZ
  • 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 https://developers.google.com/chrome-developer-tools/docs/javascript-memory-profiling
  • 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 http://slid.es/gruizdevilla/memory
  • 71. 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
  • 72. 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
  • 73. 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.
  • 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. 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.
  • 77. Contact Ivano Malavolta | DISIM + 39 380 70 21 600 iivanoo ivano.malavolta@univaq.it www.ivanomalavolta.com