drupalcon seattle - optimize your javascript · 2019-04-11 · share of web traffic by device 4%...
TRANSCRIPT
Subtitle
Add speaker name here
Title slide
Subtitle
Add speaker name here
Title slide
Saša Nikolić
Optimize your Javascript
Saša Nikolić
Developer at MD Systems
You can find me at:
● drupal.org: sasanikolic
● @sasanikolic90
● http://sasanikolic.com
Share of web traffic by device
4%Year on year changeYear on year change
52%Year on year change
43%
#
-3% +4%
Laptops and desktops Mobile phones Tablet devices
-13%
Source: We are social
Source: Source: OpenSignal
Source: Digitaltrends
Source: Source: OpenSignal
Source: Digitaltrends
Source: giphy.com
Source: Source: OpenSignal
Javascript has a cost
● Client-side framework or UI library
● A state management solution (e.g. Redux)
● Polyfills (often for modern browsers that don't need them)
● Full libraries (e.g. lodash, moment.js + locales)
● A suite of UI components (buttons, headers, sidebars, etc.)
Things are getting better Source: https://httparchive.org
From 1. 2. 2016 to 1. 2. 2019 for Drupal
JavaScript Requests JavaScript bootup timeJavaScript Bytes
The sum of kilobytes of
all external scripts
requested by the page
(minified and gzipped
code)
The number of external
scripts requested by the
page
The amount of CPU
each script consumes
per page
Time until interactive
> 15 sec!on average
Phases of a website’s loading experience
~Source: https://developers.google.com/web/fundamentals/performance/rail
Loading? Useful? Usable?
Table of content
Suggestions
Why?Why do we need to improve (mobile) JS
performance?
How to test / audit your siteTools to test the performance of your site
based on various factors.
🚀
?
Practical tips for optimizing your JS Common practices when writing JS code
Source: worldstrides.com
WorkflowHow do we know if we have a JS problem?
MONITORMonitor your site
MEASURELighthouse - performance audits
OPTIMIZEMake improvements and optimizations
2
3
1
Tools to measure1● Firefox / Chrome Developer Tools
● WebPageTest
● Google Pagespeed insights
● Google Lighthouse
● Google TestMySite
● Calibre
● Speedcurve
● Benchmark.js
● jsben.ch
● DeviceTiming
● User Timing API
Which tools can we use?
Tip:
> ls -l
ExperimentDo experiment one step at a time
11. Make one change at a time
2. Measure after every change
Lighthouse1
Source: developers.google.com
Lighthouse1
Lighthouse1
Lighthouse1
Optimize the sizeHow can we optimize our JS?
2
SMALLER SIZE BETTER CACHING
To reduce time of first page
load
To reduce time of later page
loads
Reducing the sizeHow can we reduce the size of our JS?
2
COMPRESSION
● Use gzip to compress text-based
resources
● Brotli for better compression ratio
● Zopfli
● Packer
● DojoShrinkSafe
● YUI Compressor
● try them with CompressorRater
PRECOMPRESSION
● To reduce server load
● With Webpack using simple plugins
● Or locally with brotli/gzip and deploy to
apache/nginx
Gains on first meaningful paint
MINIFICATION
● Reduce the size
○ Comments and white spaces are stripped
○ Shortens syntax
○ Converts code to abstract syntax tree (AST)
● Use UglifyJS for minifying ES5 code
● Use babel-minify or uglify-es to minify ES6
Reducing the sizeReduce the amount of JS code by minifying it
2
Reducing the sizeOptimize JS source code with prepack and
closure compiler
2
PREPACK
● Makes js code run faster
● Eliminate abstraction tags
● Compilations done at compilation
time instead of run time
CLOSURE COMPILER
● Tool to make JS download and run faster
● Compiles JS to better JS
○ Parse JS
○ Analyze JS
○ Remove dead code
○ Rewrites and minimizes what's left
Reducing the sizeReduce the size with code splitting technique
2
CODE SPLITTING
● Vendor splitting
○ Two files; for custom code and libraries
● Entry point splitting
○ Chunks per route
● Dynamic splitting
Source: https://media.giphy.com/media/
26h0oZIGGOFZdZj4Q/giphy.gif
Reducing the sizeRemove extra dependencies with Tree Shaking
2
TREE SHAKING
● A form of "dead code elimination" - Rollup
● Removes unused dependencies
Source: https://www.keycdn.com/
blog/tree-shaking
Reducing the sizeExample of Tree Shaking technique
2
Reducing the sizeEffective example of Tree Shaking technique
2
modules.js index.js
Reduced size of up to 30%
Always look for new solutionsTry new things like Next.js
2
NEXT.JS
● Try switching from react boilerplate to Next.js
○ React framework with built-in automatic code splitting, server side rendering, static
exporting…
○ Switch is invisible
○ “Free” performance with few adjustments
○ Optimised code-splitting
○ Claimed 7.5x performance increase
Caching2● Optimize subsequent loads
● Use HTTP caching
○ Determine optimal lifetimes (max-age)
○ Supply validation tokens (ETag)
● Use long-term caching, see filename hashing.
Caching2● Use Service workers
○ Rich offline experiences
○ Periodic background sync
○ Push notifications
More optimizationsMore useful optimizations
● Lazy “on demand” loading based on breakpoints
● Prebrowsing
○ Preload
○ Prefetch
○ Preconnect
2
Micro optimisationsA list of useful tips
● Use HTTP/2
● Use native js functions like
getElementById() and constructs
● Batch your dom changes
● Mind your event handlers
● Use click() instead of mouseup()
● Cut down your scope chain
○ Use the local scope
● Use async and defer
● Use requestAnimationFrame() to speed up
animations
● Use throttle and debounce
● Use css3 effects instead of js
2
Micro optimisationsA list of useful tips
● Reduce global variables
○ Define variables in a global object or in
closures
● Declare variables outside of for loops
● Use === instead of ==
● eval() = evil
○ eval("obj." + id); instead obj[id]
● Don't omit curly braces and semicolons
● Place scripts at the bottom of the page
● Comment your code
● Don't pass a string to setInterval or
setTimeOut
● Don't use with statement
● Use {} instead of new Object()
● Use [] instead of new Array()
● Utilize JS Lint
● Read, read, read...
2
Subtitle
Add speaker name here
Title slide
Software ages like milk, not like wine
Unknown
“ “
MonitorHow can we monitor our JS?
3● Check the weight of external libraries (i.e. moment.js -> locale-fns, date-fns, dayjs)
○ Source-map explorer
○ Webpack bundle analyser
● Audit 3rd party libraries
○ Do they provide any value?
○ Lazy load embeds
● Polyfills (i.e. for JS promises)
● WRITE TESTS!
GOALS
- KNOW THE PURPOSE AND END USERS
- DON’T FORCE THE USE OF JS
- ADOPT PERFORMANCE BUDGETS & CULTURE
< 5s first-load < 2s subsequent
Subtitle
Add speaker name here
Title slide
Join us forcontribution opportunities
Friday, April 12, 2019
9:00-18:00 Room: 602
Mentored Contribution
First TimeContributor Workshop
GeneralContribution
#DrupalContributions
9:00-12:00 Room: 606
9:00-18:00 Room: 6A
Subtitle
Add speaker name here
Title slide
What did you think?
Locate this session at the DrupalCon Seattle website:
https://events.drupal.org/seattle2019/sessions/optimize-your-javascript
Take the Survey!
https://www.surveymonkey.com/r/DrupalConSeattle
SourcesHelpful links
● https://developers.google.com/web/fundamentals/performance/rendering/optimize-javascript-
execution
● https://alistapart.com/article/responsible-javascript-part-1
● https://medium.com/@addyosmani/the-cost-of-javascript-in-2018-7d8950fbb5d4
● https://infrequently.org/2017/10/can-you-afford-it-real-world-web-performance-budgets/
● https://developers.google.com/web/fundamentals/performance/rail
● https://www.youtube.com/watch?v=Gl8vucNqtZQ&t=717s
● https://css-tricks.com/the-bottleneck-of-the-web/
Subtitle
Add speaker name here
Title slideThank you!