Fast mobile web apps

  • Published on
    07-May-2015

  • View
    1.148

  • Download
    0

DESCRIPTION

Slides of the talk I gave at the GDG MeetsU 2014 @L'Aquila (Italy).

Transcript

<ul><li>1.Gran Sasso Science Institute + Universit degli Studi dellAquila Ivano Malavolta Fast mobile web apps </li></ul> <p>2. Intro You will leave this presentation with...an understanding of what makes a mobile web app slow techniques to improve the performance of your mobile web 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 3. Roadmap Use the DOM efciently Master events Be smart with the network Take care of memory issues Take advantage of CSS3 featuresThe best practices and advices in this presentation are implemented in a generic app template available here:https://github.com/iivanoo/cordovaboilerplate 4. Always cache elements from the DOM every time you do $(id) the browser must parse the whole DOM 5. Minimize DOM reows A reow 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 xed widths and heights (when possible) Avoid changing elements of the DOM They change the appearance of the DOM, but do not trigger a reow op Reow: the browser process for calculating positions and geometries for HTML DOM elements 6. Keep your DOM slim Reow operations are much heavier when the number of nodes in the DOM is large there are deeply nested DOM nodesDocumentHTMLBody Element Element Element Element Element Element Element Element Element 7. Navigate the DOM with built-in methods Avoid to continuously query the DOM if you can reach specic DOM nodes using its built-in methods 8. 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.rstChild retrieves the rst 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 9. Avoid to interact with the DOM too oftenEvery time you append a node in the DOM, a reow operation is triggered 10. Prefer built-in JavaScript methods Under the lines, all JS frameworks end up in calling standard JavaScript methodswhen its possible, prefer JavaScript built-in methods to pass through a frameworkMany frameworks contain a lot of workarounds and fallbacks for older browsers that we are not targeting (e.g., Internet Explorer 7) 11. 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.parentNode.removeChild(element); remove the node from the DOMelement.hasAttribute(" attribute") tests whether the DOM node has a specic attribute element.getAttribute(" attribute") returns the value of a specic attributeelement.setAttribute(" name", " value ") adds a specic attribute to the DOM node element.removeAttribute(" attribute") removes a specic attribute to the DOM node 12. Examples of built-in JS methods element.classList.add() adds a specic class to the DOM element.classList.remove() adds a specic class to the DOM element.classList.toggle() adds a specic class to the DOM... and many more 13. Avoid using Regular expressionsA complex Regex can be a performance killer when its possible, prefer HTML5 form validation attributes or String operations 14. Avoid using Regular expressionsIf the input of a form is known a priori, use HTML5 input types http://mobiforge.com/design-development/html5-mobile-web-forms-and-input-types date tel number 15. Roadmap Use the DOM efciently Master events Be smart with the network Take care of memory issues Take advantage of CSS3 features 16. Events name of the event callback function manage the event in the capture phase data about the event 17. Capturing and bubbling When an event is triggered in the DOM,it will always start from the ROOT, and then it can be:captured by all the elements containing the target element event capturingcaptured rst by the target and then BUBBLE up through allthe HTML elements containing the target event bubbling http://www.kirupa.com/html5/event_capturing_bubbling_javascript.htm 18. Event delegationDelegationThe act of establishing event handlers at higher levels in the DOM than the items of interest 19. Event throttling delaynumber of milliseconds functionthe function to be executed Useful whenhandling events with very high frequencies and whose execution rate must be limited ex. drag, scrolling, etc. Throttling limits the execution rate of the function 20. Event debouncing delaynumber of milliseconds functionthe function to be executed Useful whenhandling events with very high frequencies and that must be executed once ex. toggle state, Ajax request, etc. Debouncing guarantees that the function will be executed only once 21. Throttling VS debouncing ThrottlingDebouncingBen Almans famous implementations available here: http://benalman.com/projects/jquery-throttle-debounce-plugin/ 22. Roadmap Use the DOM efciently Master events Be smart with the network Take care of memory issues Take advantage of CSS3 features 23. Network usage Try to prefetch data as much as possible (possibly analysing their results in 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 unpredictable and memory consuming resource you have http://fgnass.github.io/spin.js 24. Roadmap Use the DOM efciently Master events Be smart with the network Take care of memory issues Take advantage of CSS3 features 25. Take care of memory issuesTrue, 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 Denition of memory leak A memory leak is the situation in which the available memory of your app gets gradually lostIn 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? 26. Meet your best friend! 27. The retaining tree The garbage collector cleans up the portions of tree isolated from the root nodeIn our apps the window object is the root of the treehttps://developers.google.com/chrome-developer-tools/docs/javascript-memory-proling 28. Rules of thumb Better than de-referencing 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 useUse local scope Unbind event listeners Manage local cache http://slid.es/gruizdevilla/memory The key is to always have an healthy retaining tree 29. 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 J 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 30. Examples of pattern http://goo.gl/UAZQvl No memory leak Memory leak detectedNOTHING IS FREEIts normal that during the investigation your memory grows You have to pay for what you are doing in your app 31. How to detect the source of your memory leak 1. Open the Heap Prole2. Take a heap snapshot 3. Perform suspicious actions 4. Take a heap snapshot 5. Perform suspicious actions again 6. Take a nal heap snapshot 7. Select the most recent snapshot taken 8. nd the drop-down that says "All objects" and switch it 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 nd the objects which have not been collected during the snapshots 32. How to detect the source of your memory leak Now, start from the rst object and check which references it is holdingShallow size the size of the object Retain sizethe size of memory that can be freed once an object is deletedYellow DOM nodes Red DOM nodesDetached DOM trees, no JS object is directly referencing them, but they are alive some JS object is referencing them Detached DOM tree is a subtree of the DOM that1) has been removed from the DOM, and 2) cannot be GCed because some JS object is still indirectly referencing it 33. Example http://goo.gl/UAZQvl #leafmaintains a reference to it's parent (parentNode) and recursively up to#tree,so only when leafRef is nullied the WHOLE tree under#treecan be GCed. 34. Roadmap Use the DOM efciently Master events Be smart with the network Take care of memory issues Take advantage of CSS3 features 35. Rule of thumbCorollaries: Dont use JavaScript for UI-related operations Dont use images for something you can do with CSS CSS3 has many interesting features, like: text manipulations &amp; effects visual effects media queries ... If you can do something with CSS, do it! 36. Text transforms text-transform none | capitalize |lowercase | uppercase 37. Text effects 2px horizontal shadow10px vertical shadow5px blur distance#FF0000 color 38. Visual effectsThree main mechanisms:1. Transforms (both 2D and 3D) 2. Transitions 3. Animations 39. Transforms A transform is an effect that lets an element change shape, size, position, You can transform your elements using 2D or 3D transformationshttp://bit.ly/IroJ7S 40. Transforms http://bit.ly/IrpUnX 41. Transforms http://bit.ly/IrpUnX 42. TransitionsThey are used to add an effect when changing from one style to anotherThe effect will start when the specied CSS property changes value initial state nal state Intermediate states automatically calculated time 43. Transition exampleProperties: property name of a CSS property duration #seconds to complete the transition timing-function - linear, ease, delay- when the transition effect will start 44. Animations An animation is an effect that lets an element gradually change from one style to anotherYou can change style in loop, repeating, etc. initial statenalstate Intermediate states automatically calculated time 45. Example of animation result in http://goo.gl/ejp4Fy 46. Transition VS animation Trigger Transitions must be bound to a CSS property change Animations start autonomouslyStates Transitions have start and end states Animations can have multiple statesRepeats Transitions can be perfomed once for each activation Animations can be looped 47. Media queries They allow you to to change style based on specic conditions For example, they can be about devices display size orientation of the device resolution of the display ... http://bit.ly/I5mR1u 48. Examples Retina Displays iPad in landscape orientation iPhone and Android devices 49. References https://developer.mozilla.org/en-US/docs/JavaScript/Guide https://github.com/iivanoo/cordovaboilerplate 50. + 39 380 70 21 600 Contact Ivano Malavolta |Gran Sasso Science Institute iivanoo ivano.malavolta@univaq.it www.ivanomalavolta.com </p>

Recommended

View more >