Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Web Performance - Techniques You Can Apply Now

Web Performance - Techniques You Can Apply Now

14 rules and 17 techniques for faster-loading websites. Check this checklist: https://checklist.com/web-performance-checklist/

https://meetabit.com/events/helsinkijs-february-2018

Asher Shekhamis

February 12, 2018
Tweet

More Decks by Asher Shekhamis

Other Decks in Programming

Transcript

  1. Why checklists work? • "The Checklist Manifesto: How to Get

    Things Right". • Organizational tools. • When and where? • In all the situations where the human memory is fallible. • KISS - Keep It Simple, Stupid.
  2. Why checklists work? • "The Checklist Manifesto: How to Get

    Things Right". • Organizational tools. • When and where? • In all the situations where the human memory is fallible. • KISS - Keep It Simple, Stupid. • 6-7 items in a checklist. • Up to 10-12 when it becomes a habit.
  3. The Performance Golden Rule • Backend optimization ◦ Compilers ◦

    Database indexing and optimization ◦ Memory management • less than 10–20% of the response time getting the HTML document from the web server to the browser. • Focus on the other 80–90% of the end user experience.
  4. Reason Behind That Rule • More potential improvement when focusing

    on the front-end. • Frontend improvements typically require less time and fewer resources ◦ Redesigning application architecture and code ◦ Finding and optimizing critical code paths ◦ Adding or modifying hardware ◦ Distributing databases • These takes week or even months.
  5. The Performance Golden Rule Only 10–20% of the end user

    response time is spent downloading the HTML document. The other 80–90% is spent downloading all the components in the page.
  6. Image Optimization • 64% of a website’s page weight is

    made up of images. – HTTP Archive, 2016 • KeyCDN survey: 46% of the web performance experts said image optimization is the number one focus. • `compress-images`, `image-optimize-loader`, `imagemin`/`gulp-imagemin` • Google's WebP lossless images are 26% smaller than PNGs and 25-34% smaller than JPEG images.
  7. Serving Scaled Images • Do not rely on CSS to

    scale them down. • "Optimization suggestion: By compressing and adjusting the size of the image you can save 8.3 KB (34%)." • This recommendation refers to the images being scaled down by the browser. • Upload images at scale • Upload multiple resolutions of your images • It is not always possible to avoid scaling with CSS • `srcset` and `sizes` attributes
  8. Reducing HTTP Requests • The more HTTP requests your web

    page makes the slower it will load • To reduce HTTP requests: ◦ Inline your Javascript (only if it is very small) ◦ Using CSS Sprites (`background-position`) ◦ Reducing 3rd party plugins, libraries and frameworks that make a large number of external requests ◦ Combining your CSS and JS files (Not necessary when supporting HTTP/2) • Don’t generate requests for things aren’t in use • Don't load a js file that is not being used in the page in multipage web application/site
  9. Reducing HTTP Requests • Lazy load js files that are

    not in use in the current loaded page • Use inline images with `data:` URL schema
  10. Using Content Delivery Network to Reduce Network Latency • Application

    server close to user > improve response time of one HTTP request • Component web server close to the user > improve response time of many HTTP requests • CDN can dramatically decrease the website/application latency. • 50% of the 1-second page load time budget on mobile is taken up by network latency overhead. - WPT • The median desktop latency ranged from 65-145 milliseconds
  11. Using CDN • KeyCDN experiment • The latency between their

    origin server (without a CDN) and their POPs (with a CDN) on average is decreased by 73%!
  12. Consider HTTP/2 • HTTP/2 adoption across the board - Jeff

    Atwood • Benefits ◦ Multiplexing and concurrency ◦ Stream dependencies ◦ Header compression ◦ Server push ◦ No need for other HTTP/1.1 optimization practices: CSS sprints, resource in-lining and concatenation
  13. Caching and Adding HTTP Expire Headers • Web servers utilize

    `Expires` header to inform the client that the copy it holds of the component is valid until a specified time. • Example: `Expires: Wed, 28 Feb 2018 23:59:59 GMT` • `Expires` uses a specific date > stricter clock synchronization • Expiration dates have to be constantly checked • A new date must be provided in the server’s configuration • `Cache-Control` header uses `max-age` directive • Example: `Cache-Control: max-age=604800`
  14. Caching and Adding HTTP Expire Headers • 39% of visitors

    has primed cache (anasshekhamis.com) • Using a far future `Expires` header • What if those components changed? • Use "Revving Filenames" • Example: `img_2.1.png` or `img.png?v=2.1`
  15. Avoid Redirects (301) • Redirects generate extra Round Trip Times

    (RTT) • Redirect use ◦ Website redesign ◦ Tracking traffic flow ◦ Counting ad impressions ◦ Creating user friendly URLs • They delay the delivery of the HTML document. • Nothing can be rendered (User Experience)
  16. Avoid Redirects (301) Sol. • Avoid "Missing Trailing Slash" ◦

    Example: https://anasshekhamis.com/2018/01/01/docker-architecture-and-ecosystem > https://anasshekhamis.com/2018/01/01/docker-architecture-and-ecosystem/ • Use `Referer` logging to track inbound traffic patterns • Use `beacon` to track outbound traffic patterns • Pretty URLs should be part of the design (UX)
  17. Fix 404 • 404 can be expensive to the server

    • On average sites, it would cost 10-15 MB of memory • CMS like Drupal (average sites) has a 60-100 MB of memory • Broken link checker ◦ http://www.brokenlinkcheck.com ◦ https://www.screamingfrog.co.uk/seo-spider/
  18. Make JS and CSS External • External JS and CSS

    files can be cached • HTML document size is less • Reusability
  19. • Progressive Rendering • Jakob Nielson: progress indicators have three

    main advantages ◦ They reassure the user that the system has not crashed but is working on his or her problem ◦ They indicate approximately how long the user can be expected to wait, thus allowing the user to do other activities during long waits ◦ Provide something for the user to look at, thus making the wait less painful • Putting stylesheets near the bottom of the document prohibits progressive rendering • Browsers block rendering to avoid redrawing elements if their styles change Render Blocking Resources
  20. • The blank white screen phenomenon • Some browsers have

    what is known by flash of unstyled content phenomenon Render Blocking Resources Place CSS at the top of the page, and use media queries to mark some CSS resources as non-render blocking.
  21. • What about JS? • http://stevesouders.com/hpws/js-middle.php • This occurs because

    the script blocks parallel downloading. • Reasons to that behaviour ◦ The script may use `document.write` to alter the page content. ◦ To guarantee that the scripts are executed in the proper order • With scripts, progressive rendering is blocked for all content below the script > Moving scripts lower in the page Render Blocking Resources
  22. Render Blocking Resources Place JS at the bottom of the

    page, and use the `async` or `defer` directive to avoid render blocking.
  23. Web Font Performance • 70% of websites are now using

    custom fonts - HTTP Archive • Add extra HTTP requests to external resources
  24. Web Font Performance Sol. • Prioritize based on browser support

    • Choose only the styles you need • Keep character sets down to a minimum • Host fonts locally or prefetch • Store in LocalStorage with Base64 Encoding • Consider CDN
  25. Time To First Byte (TTFB) • Measurement of the responsiveness

    of a web server • HTTP request time + Process request time + HTTP response time
  26. Time To First Byte (TTFB) Improvement • Using a fast

    web host • Using a CDN • Using a reliable DNS provider
  27. Prefetch and Preconnect • Form: <link rel="prefetch" href="(url)"> • Informs

    the browsers that a given resource should be prefetched so it can be loaded more quickly. • Form: <link rel="dns-prefetch" href="//example-domain.com/"> • Gives a hint to the browser to perform a DNS lookup in the background to improve performance.
  28. Prefetch and Preconnect • Preconnect allows the browser to set

    up early connections • Connections such as DNS Lookup, TCP Handshake, and TLS negotiation can be initiated beforehand • Form: <link href='https://anasshekhamis.com' rel='preconnect' crossorigin>
  29. Gzip compression • HTML, CSS, and JavaScript at the server

    level before sending them over to the browser. • Easy to implement and make a huge difference. • https://checkgzipcompression.com/
  30. Gzip compression • GZIP compression saves 50% to 80% bandwidth

    and will therefore significantly increase the website’s loading speed. - Gzip • Add the following to `nginx.conf` gzip on; gzip_comp_level 2; gzip_http_version 1.0; gzip_proxied any; gzip_min_length 1100; gzip_buffers 16 8k; gzip_types text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript; gzip_disable "MSIE [1-6].(?!.*SV1)"; gzip_vary on;
  31. Reduce DNS lookups • DNS has a cost • 20–120

    milliseconds for the browser to lookup the IP address for a given hostname • The response time depends on ◦ The DNS resolver (typically provided by the ISP) ◦ The load of requests on it ◦ Our proximity to it ◦ Our bandwidth speed • DNS lookups are cached on a special caching server maintained by the ISP
  32. • However, after a user requests a hostname, the DNS

    information remains in the operating system’s DNS cache • Reducing the number of unique hostnames reduces the number of DNS lookups • Google.com is an example with only one DNS lookup • However, reducing the number of unique hostnames has the potential to reduce the amount of parallel downloading • Avoiding DNS lookups cuts response times, but reducing parallel downloads may increase response times • Reduce DNS lookups by using Keep-Alive and fewer domains. Reduce DNS lookups
  33. Hotlink protection • Restricting HTTP referrers to prevent others from

    embedding your assets • Save bandwidth location ~* \.(gif|png|jpe?g)$ { expires 7d; add_header Pragma public; add_header Cache-Control "public, must-revalidate, proxy-revalidate"; # prevent hotlink valid_referers none blocked ~.google. ~.bing. ~.yahoo. server_names ~($host); if ($invalid_referer) { rewrite (.*) /static/images/hotlink-denied.jpg redirect; # drop the 'redirect' flag for redirect without URL change (internal rewrite) } } # stop hotlink loop location = /static/images/hotlink-denied.jpg { }
  34. Tools to Pinpoint Performance Bottlenecks • Browsers DevTools • Google’s

    PageSpeen Insights • KeyCDN Website Speed Test • WebPageTest • Pingdom Website Speed Test