Have Your Cake And Eat it Too: A Primer on Performance – Good Morning PEERS! – per·for·mance



Have Your Cake And Eat it Too: A Primer on Performance – Good Morning PEERS! – per·for·mance

0 1


slides-nom-nom-perf


On Github una / slides-nom-nom-perf

Have Your Cake And Eat it Too: A Primer on Performance

  • PEERS Conf
  • Una Kravets | @una

Good Morning PEERS!

una.im/slides-nom-nom-perf

@una

Make something people love

people don't hate

People often say "Make something you love" Well. I'm not going to teach you how to do that. But I am here to take that, and turt it into "Make something people don't hate." People like cake. Let's talk about cake.
Ths cake is our product cake == a metaphor of how performance is a team effort many different roles, specialized

per·for·mance

/pərˈfôrməns/

an action, task, or operation, seen in terms of how successfully it was performed

measure of succes = crux of our job

Performance is Our Biggest Job

Performance is a mark of user success with our products, as dictionary.com just told us

Beautiful != Useable

Beautiful != Useable Useable > Beautiful

Useable > Beautiful

Useable > Beautiful if somebody cant access our content, then whats the point of putting it out there in the first place Beautiful + Useable = Delightful Experience
Amazon's calculated that a page load slow-down of just one second could cost it $1.6 billion in sales each year. - A 2009 A/B Study numerous studies -- th evidence is staggering Perf is key in product success
Google has calculated that by slowing its search results by just four tenths of a second they could lose 8 million searches per day. - FastCompany
  • That's a lot of missed ads and revenue. In fact, let's look at the numbers:

  • 8 million searches
  • $111,000/day
  • $40.5 million/year
a daily loss of $111,000, or about $40.5 Million a year
According to surveys done by Akamai and Gomez.com, nearly half of web users expect a site to load in 2 seconds or less, and they tend to abandon a site that isn’t loaded within 3 seconds.

1/4 internet users abandon a page that takes more than 4 seconds to load

performance speed vs interaction with the product - 0.1 second - system reacting instantaneously - 1.0 second - the limit for the user's flow of thought to stay uninterrupted, noticeable delay - 10 seconds is about the limit for keeping the user's attention focused on the dialogue
73% of mobile internet users say that they’ve encountered a website that was too slow to load. 51% of mobile internet users say that they’ve encountered a website that crashed, froze, or received an error. Kiss Metrics

More like 100% of users. Am I right?

We all know these pains far too well. Lets not inflict them upon others.

It's about Neuroscience

Tammy Everts -- its about neuroscience, not entitlement Comes down to 2 phenomenons: Web Stress The Doorway Effect

Web Stress

Slow pages cause “web stress”: physically measurable increased agitation and poorer concentration. because of poor short term memory. Humans aren't good at remembering things. Doorway Effect

The Doorway Effect

Doorway Effect explains why we can go searching for something in one room, walk into another room to look for it, and forget what we were looking for in the first place. This is due to our sensory memory, which works surprisingly similarly to a computer's memory bank. When presented with new stimuli, it halts the fluidity of the previous task, and can confuse us as to the task at hand.
Sensory memory = all of your senses Continuation of a fluid task example of iconic memory as a representation on the internet, each new tab is like stepping into a new room very easy for user to get distracted, move on to another task, and forget what they were trying to do or find in your app in the first place perf becomes critical for keeping users on track

UX Architecture

the base upon which the cake stands -- the crux, the core, the product users interact with and taste

Content Strategy

content is what you decide to put into the cake -- its ingredients -- you wouldn't mix onion powder and eggnog and cherries. limit yourself to only content or ingredients that blend well together and are needed to support your recipe, or app.
What is the main point of your site? What are you trying to get the user to see or do? This should be up front and center. It should be the first thing they see.

Your Product IS Your Content

Content determines the success of your product. period. If you don't stop and think about your content, nothing else I will tell you in this talk will matter that much Content optimizations are the best thing you can do to optimize performance.

Care About What Matters Most First

jQuery minified is 86kb, avg. image online is 654kb Remove 1/5 of one image and you can have all the jQuery you want
size of websites still increasing

Do I really need that?

What Is the Main Goal Here?

What Next?

What do you want your user to do next?

UI Design

visual representation of your masterpiece Designers need to understand their craft supplies and tools with which they are building differences between icing types and where to place little legos -- this parallels image choices and design decisions

Image Types

Raster, or bitmap, images are made of pixels. A pixel is a single point or the smallest single element in a display device. (can vary device to device) Vector images are mathematical calculations from one point to another that form geometrical shapes no loss of quality when scaled up

Image Types

File Types

  • jpg

  • png-8

  • png-24

  • gif

  • svg

.jpg – Lossy Format, great for photographs, images with a lot of color .png (8-bit) – Lossless Compression type, limited color range -- may be artifacts PNG-8 refers to palette variant, which supports only 256 colors, but is smaller in size. PNG-24 refers to true color variant, which supports more colors, but might be bigger .gif – Lossless with limited color range like .png 8, but .png is usually the better choice. svg - vector graphics, can be exported from illustrator or sketch
"Never put an image on the web that you haven't optimized" - Dave Rupert tell this to your clients

Compression Tools

ImageAlpha is a way of reducing colors in a png-24 to turn it into a lossy png with your consent. You manage a toolbar and make decisions TinyPNG: integrate into build tools ImageOptim goes through lossless compression algorithms to get the smallest size compressor.io <-- web version SVGO, also build tools and web version http://addyosmani.com/blog/image-optimization-tools/

Won't That Make My Beautiful Images Look Terrible And Pixelated!?

Compressive Images

Further Reading: Filament Group on Compressive Images By saving a JPG image at double size but at 0% quality and allowing the browser to scale it to fit a smaller placeholder, you can reduce the image weight whilst increasing the bit depth; great for using one image for retina and non-retina displays.

size: 109kb

size: 49kb

size: 109kb

size: 49kb

Progressive Jpegs: A Blast from the Past

There are two primary types of JPEG images, baseline and progressive Webpage Test Warns You of this A simple or "baseline" JPEG file is stored as one top-to-bottom scan of the image. Progressive JPEG divides the file into a series of scans. huge percieved performance win
they are a tiny bit bigger than baseline jpegs but thats because they load in layers and not top to bottom in this example, the size difference was only 2kilobytes Progressive JPEGs are better because they are faster. Appearing faster is being faster, and perceived speed is more important that actual speed. Even if we are being greedy about what we are trying to deliver, progressive JPEGs give us as much as possible as soon as possible. -- Ann Robson

Retina Images

goes back to the content strategy side of things -- showing why its important to understand the whole process retina images look nice on screens but are really terrible for users data plans aren't cheap reducing the number of download size download size needs to be < 1mb including images

Do I really need that?

Picturefill

if you need to use retina images, consider picturefill polyfill for the picture element and source set serve images based on a variety of conditions like screen size, viewport size, and screen resolution

Jank!

60 FPS FTW

This is a real term. Jank is any stuttering, juddering or just plain halting that users see when a site or app isn't keeping up with the refresh rate (which is 60 times per second). Think: slow, crappy, or janky parallax experience. frame rate on mobile will ALWAYS be different than on desktop -- so test on mobile jankfree.com
you can see how your page is rendering when you open the timeline mode in Chrome dev tools and select Frames Hit record, do something, stop it, inspect
Rendering in the bottom console: "Show FPS meter and "Show paint rectangles"

Layout Thrashing

Avoid the dreaded document reflow!

Layout is where the browser figures out the geometric information for elements: their size and location in the page Layout Thrashing occurs when JavaScript violently writes, then reads, from the DOM, multiple times causing document reflows. Kills performance Really bad on mobile devices
http://www.html5rocks.com/en/tutorials/speed/high-performance-animations/

Flexbox > Older Layout Models

Stolen from Here

-10.751ms

The same number of nodes Layout tree size -1247 w/flexbox

Front End Development

dev = the delivery its great if you've made a beautiful cake that tastes wonderful, but if you can't get it to your customer on time, then whats the point?
its so important to understand these distinctions avoid using bloated frameworks where we can and built elements from the core up
the ideal waterfall is this Separation of Concerns Core content: Essential HTML and CSS, usable non-JavaScript-enhanced experience Enhancement: JavaScript, geolocation, touch support, enhanced CSS, web fonts, images, widgets Leftovers: Analytics, advertising, third-party content

CMAT

  • Concatenate
  • Minify
  • Async
  • Test
and the way we will achieve that ideal waterfall is to think: CMAT

C: Concatenate

Pull your files into one to minimize requests.

Images

CSS

@import 'vendors/bootstrap';
@import 'vendors/jquery-ui';

@import 'utils/variables';
@import 'utils/functions';
@import 'utils/mixins';
@import 'utils/placeholders';

@import 'base/reset';
@import 'base/typography';

@import 'layout/navigation';
@import 'layout/grid';
@import 'layout/header';
@import 'layout/footer';
@import 'layout/sidebar';
@import 'layout/forms';

@import 'components/buttons';
@import 'components/carousel';
@import 'components/cover';
@import 'components/dropdown';

@import 'pages/home';
@import 'pages/contact';

@import 'themes/theme';
@import 'themes/admin';

Javascript

<!-- index.html // DONT DO THIS! -->
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="js/vendor/shake.js"></script>
<script src="js/vendor/fastbutton.js"></script>
<script src="js/scripts.js"></script>
<script src="js/tabTime.js"></script>
<script src="js/clickAnIngredient.js"></script>
<!-- Gulpfile.js // DO THIS INSTEAD! -->
var concat = require('gulp-concat');

gulp.task('scripts', function() {
  gulp.src(['./lib/file3.js', './lib/file1.js', './lib/file2.js'])
    .pipe(concat('all.js'))
    .pipe(gulp.dest('./dist/'))
});
images: spriting CSS: write modular Sass, and then have a manifest file to pull all of your code into one to be processed into a single css file javascript: same thing, we want as few requests to the sever as possible
The fastest HTTP request is the one not made. -Steve Souders, Head Performance Engineer, Google words to live by

M: Minify

Make those files as small as possible.

Images

CSS

body,fieldset,form,html,legend,li,ol,ul{margin:0;padding:0}h1,h2,h3,h4,h5,h6,p{margin-top:0}fieldset,img{border:0}legend{color:#000}li{list-style:none}sup{vertical-align:text-top}sub{vertical-align:text-bottom}table{border-collapse:collapse;border-spacing:0}caption,td,th{text-align:left;vertical-align:top;font-weight:400}input,select,textarea{font-size:110%;line-height:1.1}abbr,acronym{border-bottom:.1em dotted;cursor:help}*,:after,:before{margin:0;padding:0;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}html{-webkit-font-smoothing:antialiased;height:100%}body{font-family:"Carrois Gothic",sans-serif;font-weight:400;padding:2em 10% 4em;max-width:1000px;margin:0 auto;background:#eef0f0;min-height:100%;position:relative}h1,h2,h3{font-family:"Fjalla One",serif;font-weight:700}h1{font-size:3.5em;margin-bottom:.25em;color:#5ab1bb}h2{color:#4e6766;font-family:"Carrois Gothic",sans-serif;text-transform:uppercase;font-size:.9em;letter-spacing:2px}

Javascript

!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.2",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.

critical rendering path:

/[krit-i-kuh l] [ren-der-ing] [path, pahth]/

The intermediate steps between receiving the HTML, CSS, and JavaScript bytes and the required processing to turn them into rendered pixels

Before we talk about how to load your js, if you can avoid JavaScript or replace it with CSS, do that if not, you need to think about the "critical rendering path" This is all about getting your priorities in orderand what the user will see first By optimizing the critical rendering path we can significantly improve the time to first render of our pages. optimize the delivery of content, and defer the rest

A: Async

Manage How Your Scripts load with Async & Defer.

  • <script src="...">

  • <script src="..." async>

  • <script src="..." defer>

Remember your separation of concerns, and remember to separate HTML as markup, CSS as presentational, and JS as functional try not to make JS presentational if you can

Critical CSS

CSS is also a part of your critical rendering path you can make it even more performant by inlining your CSS styles
seems weird at first -- like its against old best practices, but like progressive jpgs and skinny jeans, whats old is new again
several tools to help -- bookmarklet and plugins for task runners
"We don’t need to render the entire page in one second, [just] the above the fold content." - Ilya Grigorik

T: Test

Check Your Performance

Render. Display. Interact.

the things that front end developers are concerned with: time to render, time to display, and time to interact

Chrome Dev Tools

Network Panel

Audits Panel

pagespeedtest.org

page speed index:

/[peyj] [speed] [in-deks]/

some hippie math that tells you how fast it "feels" to load your website.

- Dave Rupert
JS Load Event Fired:900ms - 2200ms
DOM Content Loaded:1000ms - 2000ms
HTTP Requests:50 - 75
Time To First Byte: 200ms - 350ms

A Look at the Numbers:

  • Time To First Byte: 200ms - 350ms
  • DOM Content Loaded: 1000ms - 2000ms
  • JS Load Event Fired: 900ms - 2200ms
  • Total Download Size: 1MB - 2MB
  • DNS Lookup: 10ms - 20ms
  • HTTP Requests: 50 - 75
the numbers all together based on North's recommendations

More Hipster Numbers:

  • First Byte Time: 85
  • Use persistent connection: 85
  • Use gzip compression for transferring compressible responses: 90
  • Compress Images: 90
  • Use Progressive JPEGs: 90
  • Leverage browser caching of static assets: 90
  • Use a CDN for all static assets: 85
  • Cited from Point North

Google PageSpeed Insights

Page Speed Insights Extension

Automate Your Performance Testing

Javascript Task Runners

Using Gulp

var gulp = require('gulp');
var psi = require('psi');
var site = 'http://www.html5rocks.com';
var key = '';

// Please feel free to use the `nokey` option to try out PageSpeed
// Insights as part of your build process. For more frequent use,
// we recommend registering for your own API key. For more info:
// https://developers.google.com/speed/docs/insights/v1/getting_started

gulp.task('mobile', function () {
    return psi(site, {
        // key: key
        nokey: 'true',
        strategy: 'mobile',
    }, function (err, data) {
        console.log(data.score);
        console.log(data.pageStats);
    });
});

gulp.task('desktop', function () {
    return psi(site, {
        nokey: 'true',
        // key: key,
        strategy: 'desktop',
    }, function (err, data) {
        console.log(data.score);
        console.log(data.pageStats);
    });
});

gulp.task('default', ['mobile']);
						
gulp

The Performance Budget

What is your maximum expenditure? How long are you willing to make your user wait? Use competitive analysis to see where you are in relation to your competition
How Fast is Fast Enough? You want to be 20% faster to be percieved as faster. say a competitors site loads in 5 seconds. 20% of 5 seconds is 1 second. So to be perceived as faster than them, you need to have your pages taking no longer than 4 seconds If your site is faster, it will convert users

14 KB

1 MB

To review, these are our goals/ideals for first byte time with gzip compression On WebPageTest, aim for a Speed Index value of under 1000. "Time to first byte": Ensure that all HTML, CSS and JavaScript fit within the first 14 KB. The value of 14 KB has been measured empirically by Google and is the threshold for the first package exchanged between a server and client via towers on a cellular connection. You don’t need to include images within 14 Kb, but you might want to deliver the markup, style sheets and any JavaScript required to render the visible portion of the page in that threshold. Of course, in practice this value can only realistically be achieved with gzip compression.
just because we have all of these great testing tools doesn't mean that they replace the real thing. Whenever you can, test with real devices. After all, experiencing the cake in context is better than someone else telling you how it tastes.

Thank You!

@una