The presentation is devoted to client side performance of a web app. All 4 presentations will help you reduce latency, enrich optimization of javascript code, discover tricky parts when working with API browser, see best practices of networking and learn lots of other important and interesting things. Enjoy! =)
10. JS performance
“Programmers waste enormous amounts of time thinking about, or worrying
about, the speed of noncritical parts of their programs, and these attempts at
efficiency actually have a strong negative impact when debugging and
maintenance are considered. We should forget about small efficiencies, say
about 97% of the time; premature optimization is the root of all evil. Yet we
should not pass up our opportunities in that critical 3%.”
Donald Knuth, Structured Programming With go to Statements
11. var person = {
name: "Nicholas",
age: 30
};
function displayInfo(){
var count = 5;
with(person){
alert(name + " is " + age);
alert("Count is " + count);
}
}
displayInfo();
Execution context
Nicholas C. Zakas - Writing Efficient JavaScript: Chapter 7 - Even Faster Websites
12. for (var i = 0; i < theArray.length; i++) {
copyOfTheArray[i] = theArray[i];
}
var len = theArray.length;
for (var i = 0; i < len; i++) {
copyOfTheArray[i] = theArray[i];
}
With caching:
Without caching:
Loops performance
13. for (var i in theArray) {
copyOfTheArray[i] = theArray[i];
}
theArray.forEach(function(it, idx){
copyOfTheArray[idx] = it;
});
forEach:
for in:
Loops performance
14. WebWorkersBring threading to JS
UI Thread:
var worker = new Worker('task.js');
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data);
}, false);
worker.postMessage('Hello World');
worker.terminate();
Worker:
self.addEventListener('message', function(e) {
//e.data === ‘Hello World’;
//process data
self.postMessage(result);
}, false);
self.close();
var blob = new Blob([
"onmessage = function(e) { postMessage
('msg from worker'); }"]);
// Obtain a blob URL reference to our worker
var blobURL = window.URL.createObjectURL
(blob);
var worker = new Worker(blobURL);
On fly:
Eric Bidelman http://www.html5rocks.com/en/tutorials/workers/basics/
15. WebWorkersPeculiarities
Dedicated Shared
available within the
creator script
available within the same
domain scripts
Workers have access to:
● The navigator object
● The location object (read-only)
● XMLHttpRequest
● setTimeout etc.
● The Application Cache
● Importing external scripts using the importScripts() method
● Spawning other web workers
Workers do NOT have access to:
● The DOM (it's not thread-safe)
● The window object
● The document object
● The parent object
Transferrable types:
● string
● JSON
● binary data (File, Blob, ArrayBuffer)
18. Event loop in JS UI Thread
...onclick XHR
state change
setTimeout setInterval
onclick XHR
state change
setTimeout
19. Long running scripts
var sum = 0;
for (var i = 0; i < 23000000; i++){
sum += Math.random() * i;
}
chunks
by count
by time
if (Date.now() - start > 100){
setTimeout(process);
} else {
process();
}
if (i % 10000 === 0){
setTimeout(process);
} else {
process();
}
20. asm.js
“use asm”;
JIT vs AOT
no need for dynamic type guards, boxed values, and garbage collection.
24. Native code
NaCl PNaCl
executes native code securely
through Software Fault Isolation
(SFI)
1. compiling the source code to a
portable bitcode format
2. translating the bitcode to a
host-specific executable.
25. Data caching
Caching is tricky. Avoid it to reduce complexity, allowing
you to focus on what matters: javascript variable
minification.
@webperftips
28. localStorage sessionStorage
Web Storage
clears when window is closed
+:
1. IE8+
2. Simple API
3. Simple sync API
-:
1. Poor performance for large data
2. Lack of indexing
3. Manual serialization
Michael Mahemoff http://www.html5rocks.com/en/tutorials/offline/storage/
if (!localStorage.checkins) localStorage.checkins = JSON.stringify([]);
33. WebSQL
+:
1. Mobile support
2. Good performance
3. Async API
4. Search is indexed
5. Transactions
-:
1. Deprecated (IE and FF)
2. Requires knowledge of SQL
3. SQL
Michael Mahemoff http://www.html5rocks.com/en/tutorials/offline/storage/
34. WebSQL
Michael Mahemoff http://www.html5rocks.com/en/tutorials/offline/storage/
this.db = openDatabase('geomood', '1.0', 'Geo-Mood Checkins', 8192);
this.db.transaction(function(tx) {
tx.executeSql("create table if not exists " +
"checkins(id integer primary key asc, time integer, latitude float," +
"longitude float, mood string)",
[],
function() { console.log("success"); }
);
});
46. Layout performance
summary
● Try to localize
changes
● Try to batch changes FastDOM
● window.requestAnimationFrame
● disable animations when possible
● don’t cause reflow
47. Fonts loadtime
1. Load only fonts you need
2. Load only charsets you need
3. Font Load Events API
Ilya Grigorik http://www.igvita.com/2014/01/31/optimizing-web-font-rendering-performance/
var font = new FontFace("FontA",
"url(http://mysite.com/fonts/fontA.woff)", {});
font.ready().then(function() {
// font loaded.. swap in the text / define own behavior.
});
font.load(); // initiate immediate fetch / don't block on render tree!
48. DOM
Inserting <br> elements liberally throughout your markup will
give the rendering engine enough breaks to stay fast for the
whole day.
@webperftips
49. <!doctype html>
<html lang="en">
<head>
...
<link rel="stylesheet" href="">
</head>
<body>
...
<script type=“text/javascript” src=""></script>
</body>
</html>
in the head to get styling asap
in the bottom of the body
non-blocking
async
defer
Document parsing
51. Frameworks
Instead of doing costly ajax calls to a server for data, simply
generate random data on the client side
and use that instead.
@webperftips
52. you might not need jQuery
IE8+
$(‘selector’) document.querySelectorAll(‘selector’)
$.ajax new XMLHttpRequest()
.animate() CSS3 Animations
.addClass() .classList.add()
.html() .innerHTML
...