Wicked Fast Websites 1

8 downloads 5249 Views 719KB Size Report
Wicked Fast Websites is a crash course in high performance responsive web ..... If your script is dependent on certain APIs that aren't supported by all browsers ...
Wicked Fast Websites

!1

Wicked Fast Websites

Wicked Fast Websites

A beginner’s guide to high-performance responsive web design

By Chris Ferdinandi http://gomakethings.com Copyright 2015 Go Make Things, LLC. Licensed under CC BY-NC-ND 4.0. Version 1.1.0

!2

Wicked Fast Websites

Share This Book! If you think someone you know would find this book valuable, share it with them. Download it for free at http://gomakethings.com/wicked-fast-websites

!3

Wicked Fast Websites

Getting Started About This Guide Wicked Fast Websites is a crash course in high performance responsive web design. If you're looking to build fast websites and web apps that work on any device, this is the guide for you. It's divided into four parts. The first, Getting Started, is the section you're in right now. It's really short. This chapter is almost done, and the one after it provides some useful metrics that you can use to convince clients and managers that they should invest money in this stuff. The next section, Device Agnostic Web Development, focuses on building websites that work on any device with a browser. You'll learn about some common responsive web design challenges and how to overcome them. Making Your Websites and Apps Wicked Fast is all about making your websites and web apps really fast. It includes a discussion on how to measure performance, and a bunch of tools and techniques you can use to speed up your sites. In the last section, I'll summarize everything we talked aboutincluding a consolidated list of all of the tools mentioned throughout the guide-and provide an action plan for getting started.

!4

Wicked Fast Websites

It at any point along the way you have questions or want help on your own project, reach out to me at http://gomakethings.com. I'd be happy to help.

What’s in this guide? Getting Started • About This Guide. That's the section you're reading right now. It's almost done. • Why This Matters. Some useful information if you need to convince a client or manager to invest money in web performance or responsive web design. Device-Agnostic Web Development • Intro to Responsive Web Design. If you've never build a responsive website before, or you did but felt like you had no idea what you were doing, start here. Otherwise, feel free to skip over this chapter. • How to support thousands of devices without losing your mind. Seriously, it can be done. • Content Parity. Or, why you shouldn't have a separate mobile version of your website. • Responsive Video. Techniques to ensure that videos look good in any viewport. • Responsive Tables. Tables tend to look terrible on small screens. But there are some ways to fix that. !5

Wicked Fast Websites

• Responsive Navigation. How to make it easy for people to navigate your site on screens of all sizes. • Common UI Challenges. A handful of small practices that will make a huge impact on the usability of your site across a wide range of devices. Making Your Websites and Apps Wicked Fast • Measuring Performance. What metrics should you look at, and how do you evaluate them? • Combining Files. Why fewer, larger files are better than many smaller ones (usually). • Better CSS Loading. An advanced technique for getting your above-the-fold content to render faster. • Better JavaScript Loading. How to load JavaScript files for better performance. • Removing Whitespace. Empty space is surprisingly heavy. • Fixing Fonts. How to optimize your web fonts for better performance. • Smarter Images. Image files are hurting your sites performance. Here's how to fix that. • Better Responsive Images. How do you present crisp, beautiful images across a wide range of viewports? • Going Native. Why ditching jQuery can have massive improvements on your website's performance. • Lightning Fast Tapping. When a good UX idea is bad for performance. !6

Wicked Fast Websites

• Compression & Expires Headers. Techniques for reducing page weight. • Latency from your CMS. A brief look at how to reduce performance issues introduced by your favorite CMS. Next Steps • A Quick Recap. A short summary of what you learned. • What's next? Where I answer the question, "What now?” • Tools. Links to all of the tools and resources from this guide. So, let's get to it then, shall we?


!7

Wicked Fast Websites

Why This Matters A few year’s ago, Google ran an interesting experiment. Based on analyst research, they increased the number of search results displayed on a single page from 10 to 30. This added about 500ms —that’s just half a second—of extra load time to the page. The result? Search traffic, and subsequently ad revenues, decreased by 20-percent. Amazon ran a similar experiment, and found that delays of as little as one-tenth of a second had a negative impact on revenue: In A/B tests, we tried delaying the page in increments of 100 milliseconds and found that even very small delays would result in substantial and costly drops in revenue. - Greg Linden

Sites are getting bigger In 2009, the average website was 320kb. By 2010, it had almost doubled to 600kb. At the beginning of 2013, that number had tripled to 1.2mb. At the time of writing, the average website had ballooned to over 2mb in size. That's six times larger than in 2009!

!8

Wicked Fast Websites

For a while, this exponential growth wasn't a problem. We took for granted that both computers and bandwidth got faster and more reliable every year. And then mobile happened.

Mobile WTF! People are accessing the web from devices with varying levels of computing power and bandwidth. Desktops and laptops, phones and tablets, TVs, watches, video game consoles. And for a growing number of people, mobile isn’t just one way they access the web—it’s the way they access the web. A study by Google and Nielsen found that 77-percent of mobile searches happen at home or at work, locations where you would expect someone to have access to a PC. I’m sure you’ve experienced this before. You’re laying on the couch, you just got comfortable, and you realize you need to look something up. Rather than getting up and walking to whatever room you keep your laptop in, you just pull out the computer you always have with you—your phone—and Google it. Harvard Business Review reported that 55-percent of Americans accessed the internet via a mobile device in 2012. The only surprising thing about that number is how low it is. But that same report also found that almost a third of all Americans used a mobile device as the primary way they access the internet. !9

Wicked Fast Websites

Mobile isn’t just one way people access the web. For a growing number, it’s the only way.

Greater Performance Expectations Amazingly, despite the varied power and bandwidth of mobile devices, users expect them to be faster than desktops. Fortypercent of visitors abandon a website that takes more than 3seconds to load. I’ve heard people argue that it doesn’t matter. 4G LTE, they say, is as fast as broadband wifi. And they’re right. LTE is awesome! Until I go into Target or Home Depot. Or I hit that patch of trees down the street from my house, where I can't even pull an EDGE network. Or when there’s a bad storm, and I still get internet, but it’s not LTE. And that’s here in the United States where we have a fantastic mobile infrastructure. In developing nations, things are far less predictable, and that’s where mobile growth is really soaring.

Mobile is overtaking desktop traffic In the summer of 2012, India had an important milestone: mobile traffic overtook desktop traffic. China passed a similar milestone

!10

Wicked Fast Websites

at the end of 2012. And in Korea, mobile search queries overtook desktop search queries. Mobile traffic is surpassing desktop traffic, and not just in developing nations. PAWS New England is a client of mine. They're an all-breed dog rescue based out of—you guessed it—New England. In May of 2011, mobile traffic accounted for just 9 percent of their overall traffic. That year, they switched from a desktop-only site to responsive web design. Twelve months later, mobile traffic was almost a quarter of all traffic to the site. And in March of 2014, mobile traffic surpassed desktop traffic, accounting for 52percent of all traffic to the site. While much of it comes from iOS devices, they had one visitor from a Nintendo DS, several from a Nintendo Wii, and an assortment of other (mostly Android-powered) smartphones and tablets.

The Perfect Storm There’s a myth about mobile users—that they’re always on-thego and distracted, fleeting consumers of content.

!11

Wicked Fast Websites

But PAWS found that people aren’t just looking at dogs. They’re submitting (lengthy) application forms and making donations, too. Losing visitors to poor performance means fewer dogs saved and less money to fund their work. We’re in the middle of a perfect storm. Websites are larger, devices are more varied and less predictable, and performance expectations are higher than ever.

Mobile-friendly, fast websites make more money • Google factors in mobile-friendliness and page speed when determining page rank. • A study by the Aberdeen Group found that sites that used responsive web design had more brand awareness, higher revenues, higher visitor-to-buyer conversion rates, higher visitor engagement, and higher average order value than nonresponsive sites. Mobile-friendly sites scored higher in virtually every important metric. • Think Tank Photo conducted a responsive redesign on their site, and saw a 188-percent increase in Black Friday revenue versus the year before. • O'Neill Clothing converted to responsive web design in 2013. They saw mobile conversion rates increase by 162-percent (compared to 71-percent on desktop devices) and mobile revenue increase by 370-percent (versus 136-percent on desktop devices). !12

Wicked Fast Websites

• Forty-percent of users abandon a website that takes more than 3-seconds to load. That number increases to 74-percent after 5 seconds. Fast, responsive websites have a direct impact on your organization's bottom line.


!13

Wicked Fast Websites

Device-Agnostic Web Development Intro to Responsive Web Design In 2010, Boston-based web developer Ethan Marcotte coined the term "Responsive Web Design" during a talk he gave at An Event Apart. Quick Note: If you’re already familiar with responsive web design, feel free to skip this chapter. Ethan defined Responsive Web Design (which I'll refer to as RWD for brevity going forward) as containing three “technical ingredients”: 1. Fluid Grids 2. Flexible Images 3. Media Queries With these three simple ingredients, you can build a site that responds to whatever viewport it's accessed in. In this section, I'll look at each of those ingredients, and provide some sample code you can use to build your first responsive website.

Fluid Grids In a desktop-specific website, it's common to use fixed pixels to define the width of elements. A site with a simple two-column !14

Wicked Fast Websites

grid-a main content area and a sidebar-might look something like this: HTML
Main Content


CSS #wrap { width: 1240px; } #wrap:before, #wrap:after { display: table; content: " "; } #wrap:after { clear: both; } #main { float: left; width: 800px; } #sidebar { float: right; !15

Wicked Fast Websites

width: 400px; }

If a visitor on that site has a viewport smaller than 1240 pixels in width, they'll see horizontal scroll bars, which makes for a pretty poor user experience. By using percentages instead of pixels, you can achieve a similar look that expands and contracts based on the size of the viewport: CSS #wrap { margin-left: -1.4%; margin-right: -1.4%; max-width: 1240px; width: 88%; } #wrap:before, #wrap:after { display: table; content: " "; } #wrap:after { clear: both; }

!16

Wicked Fast Websites

/* 1. Add box-sizing: http://www.paulirish.com/2012/ box-sizing-border-box-ftw/ */ #main, #sidebar { box-sizing: border-box; /* 1 */ float: left; padding-left: 1.4%; padding-right: 1.4%; } #main { width: 66.666666667%; } #sidebar { width: 33.333333333%; }

Ideally, you would use classes like .row and .grid-third instead of IDs so that you could repurpose the layout throughout the site, but that's a bit beyond the scope of this book. If you'd like to learn more about reusable code and responsive grids, check out Object Oriented CSS by Nicole Sullivan, or dig through the code in Kraken, my responsive boilerplate.

Flexible Images Fluid grids create a problem for images. It's possible that an image might be wider than the container it's in, causing it to spill out and overlap (or get overlapped by) other content. !17

Wicked Fast Websites

We can solve this problem with a few simple lines of CSS that give the same fluid properties as your grids to your image files: img { max-width: 100%; height: auto; }

Now, your images will display at the normal size, unless their container is smaller than they are. At that point, the image becomes fluid, resizing (at scale) to match it's container element.

Media Queries On smaller viewports, your fluid layout is going to look too smushed. Media queries let you transform your layout based on viewport size. They're the secret sauce that transforms sites from simply fluid to truly responsive. In this example, we'll adjust our layout to a single column, fullwidth layout on smaller viewports: #main { width: 66.666666667%; } #sidebar { width: 33.333333333%; } !18

Wicked Fast Websites

@media (max-width: 480px) { #main, #sidebar { width: 100%; } }

Putting it all together HTML
Main Content


CSS img { max-width: 100%; height: auto; } #wrap { margin-left: -1.4%; margin-right: -1.4%; max-width: 1240px; width: 88%; } #wrap:before, #wrap:after { !19

Wicked Fast Websites

display: table; content: " "; } #wrap:after { clear: both; } /* 1. Add box-sizing: http://www.paulirish.com/2012/ box-sizing-border-box-ftw/ */ #main, #sidebar { box-sizing: border-box; /* 1 */ float: left; padding-left: 1.4%; padding-right: 1.4%; } #main { width: 66.666666667%; } #sidebar { width: 33.333333333%; } @media (max-width: 480px) { #main, #sidebar { width: 100%; } }


!20

Wicked Fast Websites

Content Parity For a while, it was quite popular to have a dedicated desktop experience, and a simpler, more lightweight version of your site specifically for mobile devices. The philosophy behind this approach was a belief that mobile users exist in a specific and limited context: busy, distracted, and focused on only one type of information. In reality, that particular context is just one of many that can and do apply to mobile users.

Mobile Context is a Myth In The Trouble With Context, the folks at Yiibu point out that mobile users aren’t always just looking for information. They’re also reading while commuting, entertaining themselves while they wait in line, or browsing the web while watching TV. In a report from Google and Nielsen, it’s noted that: 77% of mobile searches are in a location (work or home) likely to have a PC available to them. We can’t infer intent or environment based on the size of one’s screen.

!21

Wicked Fast Websites

Time Travel and the Web In Windows on the Web, Karen McGrane writes: While you’re at work, you read a restaurant review for a new place you think sounds tasty. Come dinnertime, you grab your phone to pull up the address and location. One night on your tablet, you’re browsing articles for a report you’re writing at work. Back at your desk the next day, you struggle in vain to remember what you searched for to find those articles. Why can’t you find them again? Sound familiar? If you’re like most people, it probably does. Research from Google shows that 90 percent of people start a task using one device, then pick it up later on another device. People now expect access to the same content on any device. Not being able to find content, or being able to find it but not access it, is incredibly frustrating for users. Brad Frost keeps a running list of sites that fail at this over at WTF Mobile Web. It’s a good study in what to avoid.

Reducing Content I had a discussion with a developer who mentioned that for mobile users, he intended to share about 50-percent less content !22

Wicked Fast Websites

and reduce the steps in their checkout process to make it more efficient. I think that’s a great idea, but I don’t think it should be limited to the mobile site. If 50-percent less information is the right amount of information people need to complete their tasks, then you should only provide that 50-percent on all devices. And if visitors on laptops could use that additional information, why wouldn’t someone on a smaller screen want access to it, too? Similarly, if you can process a checkout in just two or three steps instead of five, why wouldn’t desktop users benefit from that as well?

When less is less Frank Chimero once wrote: Some things are truly diminished when simplified. I think there’s truth to that. It’s important not to simplify just for the sake of simplifying when thinking about smaller viewports. If the content is important, it should be there for everyone. And if it’s not, it shouldn’t be there for anyone.

!23

Wicked Fast Websites

The presentation may vary from smaller to bigger screens, but the content shouldn’t.


!24

Wicked Fast Websites

How to support thousands of devices without losing your mind Over the last two years, PAWS New England has been visited by over 800 different devices. These devices range from the very capable (the latest iOS and Android versions) to the very old and underpowered (a Nintendo DS and my 5 year old Kindle). Though it hasn't actually been tested on 800 devices, the site works on all of them. In this section, we'll look at techniques that you can use to support a nearly infinite number of devices, even if you can only test a small fraction of them.

The Secret Sauce: Progressive Enhancement Progressive enhancement is the secret to supporting a nearly infinite number of devices without losing your mind. So what is progressive enhancement? To quote Team Treehouse: Progressive enhancement is a layered approach for building websites using HTML for content, CSS for presentation, and JavaScript for interactivity. If for some reason JavaScript breaks, the site should still work and look good. If the CSS doesn’t load correctly, the HTML content should still be there with meaningful hyperlinks. And even if the HTML is malformed, browsers are smart enough to continue rendering what they can. Progressive enhancement typically yields a result that is robust, fault tolerant, and accessible. People that !25

Wicked Fast Websites

have the latest devices will get the most progressively enhanced experience, and people on slow connections or less capable devices will still be able to access the information. Websites don’t need to look the same in every browser, they just need to deliver core content and functionality. Progressive enhancement is about building in successive layers.

Building in Layers There are three main layers of the front-end development stack: HTML, CSS, and JavaScript. 1. Write solid, semantic markup that will logically make sense without CSS or JavaScript. 2. Next, layer in visual style with CSS, and ensure that it will work and look decent even if your JavaScript fails to load. 3. Finally, add interaction with JavaScript, but know that this is a nice-to-have rather than a need-to-have.

Progressive Enhancement with JavaScript Some of my scripts use CSS to hide and show elements. By default, I want all elements visible. They should only be hidden if the browser has the appropriate JavaScript support and my JS file successfully loads. To do that, I include this snippet in my JavaScript file: document.documentElement.className += ' js'; !26

Wicked Fast Websites

This adds a .js class to my element. I can check for this class in my CSS before hiding any content: .js .example { display: none; visibility: hidden; }

If your script is dependent on certain APIs that aren't supported by all browsers (things like query selectors and event listeners), you should check for those before running your script or adding your class: if ( 'querySelector' in document && 'addEventListener' in window ) { // Do stuff... document.documentElement.className += ' js'; }

If your JavaScript file fails to load (because of a broken URL, a corporate firewall, or a bad wireless connection), and while your visitor is waiting for it to download, all of your content is still visible and accessible. That popular JavaScript framework you're using Today's most popular MVC JavaScript frameworks—ones like Angular, Backbone, Ember, and more—render markup primarily !27

Wicked Fast Websites

using JavaScript, and therefore do not support progressive enhancement. Not only does this make them far more fragile (if the JS file fails, the user gets an empty page), performance suffers greatly as well. The folks at Filament Group found that JavaScript frameworks can take 4 seconds or more to display the first piece of content to a user. As we learned in the first section, even fractions of a second have meaningful bottom-line impacts on your business. The good news: there's a push towards isomorphic JavaScript, scripts that can be run on both the server and in the browser. You get faster initial load times from the server, and faster updates from the browser. And if the JS file fails to load, you simply fallback to the server and the visitor still gets all of your content. The bad news: We're not there yet with most of today's most popular JavaScript frameworks.

Mobile First Mobile first, from a coding perspective, means that your base style is typically a single-column, fully-fluid layout. You use @media (min-width: whatever) to add a grid-based layout on top of that.

!28

Wicked Fast Websites

The alternative—desktop first—involves starting with a wide, grid-based layout, and using @media (max-width: whatever) to scale down to a single-column layout. When we all began converting our desktop-only sites to responsive design, it was common to use a desktop-first approach because it made retrofitting easier. Mobile-first is the better more future-friendly approach. Here's an example of desktop-first code, borrowed from our chapter on RWD: #main { width: 66.666666667%; } #sidebar { width: 33.333333333%; } @media (max-width: 480px) { #main, #sidebar { width: 100%; } }

And here's that same code, rewritten mobile-first: #main, #sidebar { !29

Wicked Fast Websites

width: 100%; } @media (min-width: 480px) { #main { width: 66.666666667%; } #sidebar { width: 33.333333333%; } }

Why mobile first? iPhone and Android browsers are quite capable, but older smart phones, feature phones and other small-screen devices like gaming consoles may not support media queries. Imagine trying to read tiny text in a big screen layout on an old, underpowered feature phone. Mobile first web design extends progressive enhancement to site layout, allowing you to serve simple, readable content to all devices, and layer on structure and presentation for more capable devices. It's worth noting that IE 8 and lower do not support media queries, so they receive the basic, single-column layout when

!30

Wicked Fast Websites

using this approach. There is a simple way to address this if you really need to optimize for IE 8.

Support is not the same as optimization The web is for everyone, but support is not the same as optimization. Rather than trying to provide the same level of functionality for older browsers, use progressive enhancement to serve a basic experience to all browsers (even Netscape and IE 5), and layer in a better layout, more visually attractive elements, and an enhanced experience for newer browsers that support modern APIs and techniques. This will let you build engaging, feature rich web experiences, support any browser that can connect to the web, and maintain your sanity.

Does this mean I don't have to test my site? No. Testing on real devices will still surface unexpected layout quirks and interaction challenges. Test on as many real devices as you can, but acknowledge that you can't test everything. Come with up a sensible policy and stick to it. This seems reasonable: “We test on the current and last major release of iOS and Android. We also test on the latest versions of !31

Wicked Fast Websites

all modern browsers, as well as the latest version of IE and two versions prior.”


!32

Wicked Fast Websites

Responsive Video Earlier in this guide, I shared a simple technique for flexible images: img { max-width: 100%; height: auto; }

This ensures that image files display at their normal size when their container is big enough, but scale down in size as viewports become smaller. You can use this same technique with the new HTML5 element: img, video { max-width: 100%; height: auto; }

iFrame Videos While responsive video is easy with the HTML5 video element, it's a bit more tricky when embedding iframe videos from sites like YouTube and Vimeo. You may be thinking, “Can't you just do something like this?” iframe { max-width: 100%; !33

Wicked Fast Websites

height: auto; }

While the max-width attribute works great, height: auto causes the iframe to break it's aspect ratio and collapse to a very small, unusable height. You should instead do this: iframe { max-width: 100%; }

This will cause iframe video to display at it's normal aspect ratio, and when the container shrinks to a size smaller than the video's width, it will gracefully scale down to match. Unfortunately, the height of the iframe will remain fixed (the height of the video inside the iframe will scale), with letter-boxing above and below. For iframe videos that scale properly, use FluidVids.js by Todd Motto, in addition to the CSS above.


!34

Wicked Fast Websites

Responsive Tables Tables and small viewports don't mix very well. Some people try to duplicate the look of a table using a responsive grid. Don't do this. Tabular data, for semantic reasons, belongs in a table. Adding a max-width to your table will ensure that it doesn't flow off of the screen, though on all but the narrowest of tables content gets packed so tight that it flows out of its cell or becomes unreadable. table { width: 100%; max-width: 100%; }

Let's look at a few ways to provide a better, more usable table experience on small viewports.

Using JavaScript There are a few JavaScript plugins that enhance table functionality on smaller screens. My favorite is Table Saw by Filament Group. Table Saw provides you with a few different options, including moving the header labels down next to the appropriate data in each cell, introducing horizontal swiping, and providing a toggle to show or hide columns. !35

Wicked Fast Websites

The biggest downside to this approach is that it requires JavaScript. Older, slower devices-the ones that most need a good solution-may not get the best experience.

Pure CSS Living Social recently introduced an incredibly effective, pure CSS way to deliver responsive tables. On smaller viewports, their solution converts tables into a single column layouts, hides the header, and then pulls header labels down into each cell next to it's value for easy scanning. It uses data-label attributes on each cell, and CSS's :before, content, and attr() properties to display that value on smaller viewports. HTML !36

Wicked Fast Websites



CSS @media (max-width: 40em) { /** * Hide header/labels */ .table-responsive thead { display: none; visibility: hidden; } /** * Add a border and padding each row */ .table-responsive tr { border-top: 1px solid #808080; !37

Wicked Fast Websites

display: block; padding: 0.5em; } /** * Remove borders from individual cells. * Add padding. * Align content to the right. */ .table-responsive td { border: 0; display: block; padding: 0.25em; text-align: right; } /** * Display the data-label value before the cell content. * Make label bold, uppercase, and float to the left. */ .table-responsive td:before { content: attr(data-label); float: left; text-transform: uppercase; font-weight: bold; } }


!38

Wicked Fast Websites

Responsive Navigation How do you display navigation elements on smaller screens in a way that makes it easy for the user to move around your site, but keeps it out of the way when they're trying to perform a task? People address this challenge in a large number of ways: • An expand-and-collapse menu that slides in from the top or side of the page. • A horizontal list of links. • A select menu. • An anchor link that takes you to a vertical navigation list at the bottom of the page. • And on, and on, and on... So which one you should choose?

Responsive Navigation Guidelines There's no one right way to implement navigation for smaller viewports, but there are some guidelines you should keep in mind for a better user experience. 1. Don't use a select menu. Forms as navigation are both unsemantic and confusing to visitors.

!39

Wicked Fast Websites

2. Many solutions require the use of JavaScript. Make sure that navigation is still accessible before your JS file has loaded (or if it fails altogether). 3. An anchor link that brings you to footer navigation can be jarring and and unexpected. If you go with this approach, it may be worth animating the scroll so that visitors understand they've moved to a new location. You should also provide a link back to the original anchor link. 4. Avoid multi-level navigation patterns, as they can be quite confusing on smaller viewports. 5. If your navigation is small enough that it can displayed on one-line on smaller screens, don't hide it. Keeping the links exposed makes it easier for visitors to find what they're looking for. 6. Avoid fixed headers. They eat up valuable real estate on smaller screens. If you want to get up and running quickly, I've put together a collection of five mobile-friendly navigation patterns that you can use on your project, as well as a set of responsive drop-down menus that are designed to work well with them.

About the Hamburger You may be familiar with the “hamburger icon,” those three horizontal lines stacked one of top of the other, as a symbol for !40

Wicked Fast Websites

the navigation menu. It's an approach that was popularized, and then later abandoned, by Facebook. There's a growing body of research that the icon is confusing and not easily recognizable to many users, and that you should instead use a more obvious word like "Menu" or "Navigation". Here are some articles on it if you wanted to explore this more deeply: • Hamburger vs. Menu: The Final AB Test • Apple on Hamburger Menus • The Hamburger is Bad for You And as a counterpoint, here's some data from Bookings.com that it's really not a big deal: Would you like fries with that? Luke Wroblewski has started calling the hamburger's counterpart, three dots stacked on top of each other, as the “kebab”.


!41

Wicked Fast Websites

Common Responsive UI Challenges There are a handful of small practices-little nudges and tweaksthat will make a huge impact on the usability of your site across a wide range of devices.

Font Size For a long time, small fonts—10px to 14px in size—were very popular on the web. Fonts at this size are difficult to read on small and high resolution screens. For body copy, you should aim for 16px at a minimum. This is actually the default base font size in most browsers. It will seem too big at first if you're not use to building sites that way, but after a few weeks, anything smaller will seem absurd, and your visitors with vision challenges will thank you!

Relative Sizing Web browsers set a default font-size of 16px. If you set the font-size to 100% in your stylesheet (or didn’t set it at all), your text would render at 16px. If the visitor had changed their default font size to 20px, your text would render at 20px.

!42

Wicked Fast Websites

When you set sizes in pixels, though, nothing changes if your visitor adjusts their default font size. Many web designers like the control this gives them, but relative sizing is better for usability. It gives control to the visitor and allows people who have accessibility needs (for example, someone who’s visually impaired and needs to read at larger fontsizes) the ability to modify the content to fit their needs. Additionally, many non-desktop devices use a larger base font size to improve readability. You don’t have to worry about this breaking your layout. If all of your sizing uses relative values, then when the default font-size changes in a visitor’s browser, all of the site elements will scale with it. This also ensures that if someone uses their browser's zoom feature, you site doesn't introduces horizontal scroll bars. Not sure how to get started? Check out Working with Relative Sizing.

Click Target Size and Spacing Touch screens can be imprecise, especially for those of us that (ahem) have fat, clumsy fingers. Links and other clickable or tappable elements should have enough size and space around them that they're easily tapped.

!43

Wicked Fast Websites

How much size and spacing, exactly? From Google: You should ensure that the most important tap targets on your site—the ones users will be using the most often—are large enough to be easy to press, at least 48 CSS pixels tall/wide (assuming you have configured your viewport properly). Less frequently-used links can be smaller, but should still have spacing between them and other links, so that a 10mm finger pad would not accidentally press both links at once. Users should not have to pinch zoom (or rely on other browser UI features for disambiguating finger taps, such as Chrome's popup magnifying glass) in order to easily and reliably press the desired button or link. Recommendations on the actual pixel size of tap areas vary wildly by device manufacturer, and are impossible to accurately calculate when screen resolution and pixel density differ so greatly. Your best bet? Get your clumsiest friend and have them test your site on a variety of devices.

Hover Effects on Touch Screens Don't forget: touch screen users can't hover. Many devices will register an initial tap as a hover on hover event objects, and then a second tap as a click. On elements that have

!44

Wicked Fast Websites

both hover and click events, this forces your visitor to tap twice to complete their task, which can get be quite frustrating. Avoid hover effects when you can.

Contrast Good color contrast between your text and the background is an accessibility best practice (and in many countries a legal requirement). It can become even more important on low powered e-ink devices. Because e-ink devices leave behind remnants of previous text every few page changes, strong contrast is critical to readable text. You can use the WebAIM Color Contrast Checker to test your design. You should also try switching your monitor to grayscale, and use Color Oracle to simulate color blindness when testing your designs. To learn more about web accessibility, visit the A11Y Project.

Viewport Scaling When smart phones first came out, most websites were not designed for mobile devices. To avoid awkward horizontal scrolling on non-optimized sites, most mobile browsers pretend to have a desktop-sized width.

!45

Wicked Fast Websites

You need to tell mobile browsers that your site is mobileoptimized so that they get the appropriate zooming and scaling. Add this to the element of your site:

Some developers disable user zooming by adding things like user-scalable=no or maximum-scale=1.0. Do not do this. Zooming is a critical accessibility feature, and should not be disabled for any reason (A while ago, iOS had a zooming bug when the phone orientation was changed, but it was fixed in iOS6).


!46

Wicked Fast Websites

Making Your Websites and Web Apps Wicked Fast Measuring Performance How fast is fast enough? One second. One second is roughly the limit to keep a visitor's flow of thought on the task at hand uninterrupted. Sound impossible? It's not, but that's because there's a catch.

Measuring the right things Historically, developers have looked at things like total load time and page weight as the key metrics for performance. While those are important, there are two that matter a lot more: • Time to First Byte, which tells you how quickly your server is sending data back to the browser after a user types in your URL. • Time to Start Render, which is how quickly the browser begins displaying content to your visitor after they type in your URL. Your whole site doesn't need to load in one second for it to feel fast. It just needs to start displaying content in that amount of time. !47

Wicked Fast Websites

Perceived performance is more important than actual performance. The rest of this guide will be focused on how to improve start render time on your responsive websites.

The right tool for the job If you're serious about web performance, you should become familiar with WebPagetest. Originally built by AOL, it was opened source in 2008 and is now maintained by Google. WebPagetest provides a simple, web-based GUI that measures a ton of performance metrics about your site: • • • • •

Total Load Time Time to First Byte Start Render Time Speed Index And more!

It provides this data for both initial load and subsequent visits, and allows you to test your site on a variety of devices, from different locations, using different bandwidths. Best of all, WebPagetest provides a “filmstrip” view that shows you the site's render progress in 100ms intervals, which is insanely useful.

!48

Wicked Fast Websites

Other Important Measurements While start render time is critically important (and influenced by time to first byte), other metrics are still worth considering. Lengthy total load time can have a negative impact on a visitor's experience. Ever been on a site where content is still showing up (and shifting elements around) after 20 or 30 seconds? It's annoying. Total page weight can impact overall site speeds, but it also can have a big impact on visitors using mobile devices with restricted data plans. Tim Kadlec has put together an awesome tool called What does my site cost? that illustrates page weight in more meaningful terms. It mashes up data about your site from WebPagetest with average data costs around the globe and financial metrics from the World Bank to provide you with a few different views of what your site costs to visitors around the world. When lobbying for performance, this is nice, tangible metric to share with stakeholders.

Performance at different bandwidths One second is a nice target for high-speed connections, but it may be unrealistic at slower bandwidths. Your targets will vary,

!49

Wicked Fast Websites

but I like to see something under three seconds on a 3G network, and under five seconds on EDGE. If you can go even lower than that, all the better.


!50

Wicked Fast Websites

Combining Files One of the biggest bottlenecks in page load time is in downloading the actual files for your site. Each HTTP request adds additional load time. How much time? From a now defunct article by Google: Every time a client sends an HTTP request, it has to send all associated cookies that have been set for that domain and path along with it. Most users have asymmetric Internet connections: upload-to-download bandwidth ratios are commonly in the range of 1:4 to 1:20. This means that a 500-byte HTTP header request could take the equivalent time to upload as 10 KB of HTTP response data takes to download. The factor is actually even higher because HTTP request headers are sent uncompressed. In other words, for requests for small objects (say, less than 10 KB, the typical size of a compressed image), the data sent in a request header can account for the majority of the response time. It’s actually often faster for a browser to download one 150kb file than it is to download three 50kb files, even though the total file weight is the same. This problem will be addressed in HTTP2, but for now, combine similar file types together—a process known as concatenation—to improve page performance: !51

Wicked Fast Websites

• Combine your scripts into just a few logical groups. I use feature-detection.js and main.js. • Combine all of your CSS into a single main.css file (avoid using @import, which still requires an additional HTTP request).

Finding Files Third party scripts-especially social sharing plugins-often make multiple requests each. You can see a list of all of the scripts and styles being loaded on your site by looking at the “Network” tab in your preferred browser's developer tools. For social sharing links, try using simple HTML links instead of the vendor-provided scripts.

Tools • Sass adds programming logic to CSS, but also let's you maintain separate files that can be compiled into a single CSS file. • CodeKit for Mac compiles Sass and concatenates scripts. • Prepos for Windows also compiles Sass and concatenates scripts. • If you're comfortable with command line, Grunt or Gulp are task runners that can do almost anything. My Gulp Boilerplate can get you started.
 !52

Wicked Fast Websites

Better CSS Loading Your stylesheet is necessary for rendering content properly, but while it’s being downloaded and parsed, it also blocks any rendering from happening. To get around this challenge, an emerging technique recommended by folks like Google and Filament Group is to inline your critical path CSS. Yes, that’s right. Inline your CSS. It works like this: 1. Extract the styles that apply to above-the-fold content and load them inline in the . 2. Load your full stylesheet asynchronously so that the rest of your page can continue downloading and rendering. Sounds wacky, but it makes a big difference.

How to decide what to inline When I mentioned this technique to a few folks on Twitter, the most common question I got was how I decided what to inline. If you use a JS task runner like Gulp or Grunt, there are a few plugins that you can use to automate this: Critical by Addy Osmani and Critical CSS by Filament Group. There is also created an online generator if command line isn’t thing. !53

Wicked Fast Websites

I didn’t use any of these. I tried using them, and found that they often left out styles important for rendering my layout on smaller or taller viewports (as in, my iPhone), so I created my critical CSS manually. It's easier than you’d think!

Using Sass If you still write vanilla CSS, this may be a fair bit harder. Because I work with Sass and keep my all of my components in their own modular files, doing this manually was a breeze. I import all off my Sass components into a main.scss file. I created a second file, critical.scss, and used it to import just the critical path components, eliminating the need to write code twice or do lots of copy-and-pasting. Here are the components I included: • • • • • •

Normalize.css My grid system Typography basics Button styling SVG styles for my icons Navigation styles

• Utility classes !54

Wicked Fast Websites

The magic number The magic number you should care about is 14kb. That’s (give or take) how much data a server sends per round trip when the browser makes a request for a web page. You want your abovethe-fold content-and its associated styles and scripts—to weigh 14kb or less so that the browser can start rendering it as soon as that first packet of data is received.

How to inline and async your CSS The inlining piece is pretty straightforward. Add the contents of your critical.css file to your element inside a tag: .some-styles { font-weight: bold; } ... .etc-etc { color: #333333; }

!55

Wicked Fast Websites

Rather than adding your full stylesheet via a element as you normally would, I used loadCSS.js from the Filament Group (inlined in the ) to load it asynchronously. There’s no natively supported way to load CSS files async (as there is with JS), so this script helps prevent render blocking. function loadCSS( href, before, media, callback ){ ... } loadCSS( '/path/to/your/full.css' ); .some-styles { font-weight: bold; } ... .etc-etc { color: #333333; }

Then, I added a fallback in the footer (again, to prevent render blocking) for browsers that don’t support JavaScript or have it turned off. !56

Wicked Fast Websites



What about browser caching? Using this approach means that the browser is no longer able to take advantage of having your stylesheet cached for reuse on subsequent pages and visits. Fortunately, there is a relatively easy way to get around this, developed by the wonderfully talented folks at Filament Group: Set a cookie when the full stylesheet is loaded asynchronously, and then check for that cookie on subsequent page visits. If it’s there, skip the critical CSS inlining and just load the stylesheet via a traditional element. This does, of course, require some server-side logic. Setting the cookie with loadCSS Setting the cookie requires one additional, super lightweight script from the Filament Group, onloadCSS.js, that runs a callback when the CSS file is loaded. function loadCSS( href, before, media, callback ){ ... } function onloadCSS( ss, callback ){ ... } !57

Wicked Fast Websites

var stylesheet = loadCSS( '/path/to/your/ full.css' ); onloadCSS( stylesheet, function() { var expires = new Date(+new Date + (7 * 24 * 60 * 60 * 1000)).toUTCString(); document.cookie = 'fullCSS=true; expires=' + expires; });

The example code above sets a cookie called fullCSS that expires after a week.

A Case Study If you're a WordPress user and want to learn how to implement the server-side logic on your site, you might enjoy my personal case study on implementing this: Inlining critical CSS for better web performance. I was able to shave 40% off of my start render time, bringing it down to below half a second.


!58

Wicked Fast Websites

Better JavaScript Loading Like your CSS, JavaScript also blocks content rendering. Unlike CSS, it also stops all other files from downloading until it has been downloaded and parsed. Normally, a browser will download two assets from the same source at once. This is important because it means that one large file won't become a bottleneck for other files. However, because JavaScript often makes additions or changes to the DOM, the browser stops everything and waits until it's parsed before continuing. That's smart, but it also means that your scripts can have both real and perceived negative impacts on performance. So what can you do about it?

Be smart about script location in the markup Feature detection scripts (like Modernizr) may affect how CSS renders content, so they should go in the . Ideally they're small and lightweight, and you'll inline them so the browser doesn't have to wait for a file to download before running them. Some browsers support the use of the async attribute on a tag. This tells the browser that it shouldn't block rendering or prevent other files from downloading while the script itself downloads. !59

Wicked Fast Websites

Unfortunately older browsers, including IE9, and newer but lightweight browsers like Opera Mini, do not support it. They'll simply ignore it and treat the script as a normal, render-anddownload blocking file. Instead, move any non-essential scripts into the footer, after all of your content. This allows all of your content and associated files to download and render first, improving the perceived performance of your site.


!60

Wicked Fast Websites

Remove Whitespace Minification is the process of removing spaces, line breaks and comments from your CSS, HTML, and JavaScript. Though it might not seem like a big deal, removing all of that unused whitespace can decrease the size of your files by 40-percent or more. So what should you minify? CSS and JavaScript always. If your CMS provides an easy way to minify your HTML, minify that, too.

Tools Removing all of the whitespace from your files by hand would be insane. There are a bunch of tools that make it easier: • CodeKit for Mac minifies files as part of it's build process. • Prepos for Windows also minifies files as part of it's build process. • Google's PageSpeed Insights is a web-based GUI that let's you download optimized versions of your files. • If you're comfortable with command line, Grunt or Gulp are task runners that can do almost anything. My Gulp Boilerplate can get you started.

Working with minified files Minified files are essentially unusable if you need to make updates or changes. Everything is on a single line, and with

!61

Wicked Fast Websites

JavaScript files, your intuitive variables are often renamed to single letters for even better size reduction. Keep an un-minified version of your file that you use for development. Save your minified version as a separate file with a .min suffix. This also makes debugging easier during the development phase.


!62

Wicked Fast Websites

Fixing Fonts Loading web fonts often results in a Flash of Invisible Text (FOIT) that leaves the page unusable until it loads. Ilya Grigorik, a web performance engineer at Google, reports: 29% of page loads on Chrome for Android displayed blank text: the user agent knew the text it needed to paint, but was blocked from doing so due to the unavailable font resource. In the median case the blank text time was ~350 ms, ~750 ms for the 75th percentile, and a scary ~2300 ms for the 95th. Even the median value of 350ms is an unacceptable performance hit. Fortunately, there's a simple fix.

Asynchronous Font Loading Use loadCSS to asynchronously load your web font stylesheet. This prevents the render block from happening, and when the web font has downloaded, the browser will switch over to the new typeface. You will end up with a small “jump” as your site switches from your fallback font to your web font after it loads, but I believe it's worth it for the notable improvements in perceived performance.

!63

Wicked Fast Websites

Let's say you wanted to load Open Sans from Google Web Fonts. You might normally add this to your site:

Instead, do this: function loadCSS( href, before, media ){ ... } loadCSS( 'http://fonts.googleapis.com/css? family=Open+Sans:400italic,700italic,700,400' );

Delayed FOIT If you look at the filmstrip view in WebPagetest, there is actually sometimes still a flash of invisible text. It happens after the page has already been rendered in your fallback font, just as the web font is loading. It's typically so quick that you won't actually see it. It just shows up in the filmstrip view. All things considered, I would still asynchronously load the web font. It gets content in front of the visitor faster, which improves perceived performance.


!64

Wicked Fast Websites

Smarter Images Images now account for more than half of the total weight of an average web page. They are an important part of an engaging web experience, but we can be smarter about how we use them. The convergence of high-density displays and mobile, lowbandwidth computing puts two competing interests at odds. Your site performs better-particularly on spotty mobile networkswhen images are smaller, but looks worse when viewed on highresolution screens. And some of the highest resolution screens are found on tablets and smartphones, which often have unpredictable internet connections. In this chapter, we're going to explore a variety of techniques that you can use to find the right balance between aesthetics and performance with the images on your website.

Picking the Right Format Different image formats work better for different types of graphics. PNG is a lossless image format, so it keeps graphics sharp and crisp (as opposed to the lossy JPG format). For icons and simple images with clean lines, they can actually be more lightweight than JPGs. But for photos and images with lots of visual noise, JPGs will be much smaller in size with comparable quality. !65

Wicked Fast Websites

Picking the right JPG Format The JPG actually has multiple formats. The most common on the web is the baseline JPG. Baseline JPGs start rendering at the top, and build down as they go. An alternative format that was popular a decade ago and is seeing a bit of a comeback is the progressive JPG. Progressive JPGs build in layers. Initially, the full image in low resolution is displayed, and as the image renders, it becomes increasingly crisp and clear.

While progressive JPGs are typically a little smaller in size than baseline JPGs, their real advantage is that they appear faster to the user because they display more of an image at once. And on !66

Wicked Fast Websites

smaller screens, the lack of clarity on initial renders may not even be as noticeable. While all browsers display progressive JPGs, some browsers do a better job than others. For “non-supporting” browsers, the entire progressive JPG needs to download before it can be displayed, resulting in a worse experience than a baseline JPG.

Compress Your JPGs Photos can add a lot of weight. A high-quality photo can weigh upwards of 1mb or more. By compressing photos, you can reduce them down to a fraction of their original size while maintaining image quality. A JPG compression rate of 70 is considered high-quality for the web.

SVGs JPGs, PNGs, and GIFs are raster images. They have specific pixels assigned to specific locations that render images at a specific size. SVGs, or scalable vector graphics, use geometric shapes and mathematical relationships to render images. As a result, you can scale them up or down in size infinitely and they never lose their crispness or degrade in quality. !67

Wicked Fast Websites

For detail-heavy graphics, like photographs, they can end up being much larger than a high-resolution JPG, but they're perfect for icons and simple images. You can also style them with CSS, which makes it easy to do things like changes colors, add hover effects, and more. Which method for including SVGs should you use? There are many ways to use SVGs, including simply including them as the src in an element. Because SVGs are really markup files, my preferred method is to copy-and-paste the contents directly into my HTML. This gives me more flexibility in styling them, and eliminates an HTTP request. Browser Support SVG is well supported in IE 9 and up, all modern browsers, and Opera Mini. I implement a simple feature text inline in the to check for browser support. This adds an .svg class to the element, which you can use to add fallback content. ;(function (window, document, undefined) { 'use strict'; var supports = !!document.createElementNS && !! document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect; // SVG feature detection if ( supports ) { // If SVG is supported, add `.svg` class to element !68

Wicked Fast Websites

document.documentElement.className += (document.documentElement.className ? ' ' : '') + 'svg'; } })(window, document);

I add a class to my CSS for supporting text. It’s always accessible to screen readers, but only visually displayed if SVGs are not supported. /** * Hide fallback text content if browser supports SVG */ .svg .icon-fallback-text { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; }

You would use it like this. ... Tweet This !69

Wicked Fast Websites



Learn more To learn about how to create and use SVGs, check out my how-to guide, and take a look at Icon System with SVG Sprites and SVG is for Everybody, both from Chris Coyier.

Smush Your Images The metadata that photographs include—timestamps, color profiles, and such—can add quite a bit of weight. Smushing is the process of removing that metadata, and it can reduce the size of an image by more than 25-percent. If you’re a Mac user, ImageOptim will smush your images without degrading the quality. It works for PNGs, JPGs, and GIFs. Windows lacks a clear one-for-one desktop app counterpart, though there are a handful of products that work well for different image types. If you’re a Windows user, check out b64.io, a web-based, drag-and-drop optimizer that seems to work just as well as ImageOptim. SVGs often have a lot of junk and metadata in them, too, put there by your graphic design software. SVGO is a great crossplatform tool for optimizing your SVGs. If you're allergic to command line, Jake Archibald created SVGOMG, a GUI for SVGO.


!70

Wicked Fast Websites

Better Responsive Images Why would you send the same image to a five-year old feature phone or a tiny smart watch that you would to a modern laptop attached to 32-inch, high-definition monitor? Earlier in the guide, I shared this technique for responsive images: img { max-width: 100%; height: auto; }

That's great for resizing the one image you do send, but wouldn't it be great if you could send different images based on things like viewport size and screen density? Well, you can! Let's look at a few different ways to do that.

Background Images You can load viewport-aware background images using media queries. You can even use different images based on screen density. .background-img { background-image: url("/path/to/the/imagesmall.jpg"); !71

Wicked Fast Websites

} @media (min-width: 30em) { .background-img { background-image: url("/path/to/the/imagemedium.jpg"); } } @media (min-width: 40em) { .background-img { background-image: url("/path/to/the/imagelarge.jpg"); } } @media (min-width: 60em) { .background-img { background-image: url("/path/to/the/imagexlarge.jpg"); } }

Most browsers will only load the image required for the current viewport size. If a visitor resizes their browser or rotates their device, and this triggers a new break point, a subsequent image download will occur, but the benefits of using smaller sizes outweigh the edge case of a potential second download. Of course, you're not always going to use a background image, which brings us to... !72

Wicked Fast Websites

The element and srcset Being able to specify which version of an image to show at which breakpoint sounds great. And in many cases, it is (think art direction across a variety of viewports). But it also involves a lot of math and decision making on your part that really should be offloaded to the browser. Rather than figuring which image to send and when, imagine if you could just tell a browser the sizes it has to choose from and let it figure out which image works. This opens up the door for some interesting opportunities: • Browsers could automatically figure out which image would look best given the device's screen resolution. • Visitors could choose to prioritize performance over aesthetics, forgoing, for example, the high-resolution images when in low bandwidth conditions or if trying to conserve data. • Browsers could determine that grabbing the highest required resolution for an image and downsizing on orientation change makes more sense than a second download (or vice-versa). Today, you as the developer are making decisions that really belong in the hands of the visitor and their browser. Fortunately, a pair of solutions are in the works.

!73

Wicked Fast Websites

The element The element let's you serve different images based on breakpoints:

The srcset attribute The srcset attribute allows you to provide a few image choices, and share some information with the browser that helps it decide which image to choose. It can be used with a standard element, or with the element.

!74

Wicked Fast Websites

Browser Support Currently, support for srcset isn't great, and support for the element is even worse, but support will get better in the near future. However, the [Picturefill polyfill from Filament Group let's you use both methods today. When support improves in the future, you can simply remove the polyfill. To learn more about these approaches and how to use them, check out Srcset and sizes by Eric Portis.


!75

Wicked Fast Websites

Going Native One of the benefits of a framework like jQuery is that it smooths out all of the weird browser inconsistencies you might run into. But, all that abstraction and extra code adds a lot of weight and performance latency to a site. Tim Kadlec writes... It’s not just download sizes that you should be worried about. In a presentation given at Velocity in 2011, Maximiliano Firtman pointed out that on some phones (older, but still popular, BlackBerry devices for example) can take up to 8 seconds just to parse jQuery. More recent research from Stoyan Stefanov revealed that even on iOS 5.1, it was taking as many as 200-300ms to parse jQuery. Tim’s got some updated data, and while modern iOS and Android devices are lightning fast, older models—including ones that are still on the market—performed much more poorly.

My approach The web is for everyone, but support is not the same as optimization. Rather than trying to provide the same level of functionality for older browsers, I use progressive enhancement to serve a basic !76

Wicked Fast Websites

experience to all browsers (even Netscape and IE 5). Newer browsers that support modern APIs and techniques get the enhanced experience. To be clear, I’m not advocating dropping support for older and less capable browsers. They still have access to all of the content. They just don’t always get the same layout or extra features.

Cutting the mustard I use a feature detection technique that the BBC calls “cutting the mustard.” A simple browser test determines whether or not a browser supports modern JavaScript APIs. If it does, it gets the enhanced experience. If not, it gets a more basic one. var supports = !!document.querySelector && !! window.addEventListener; if ( !supports ) return;

The !! converts the API method into a boolean value that you can test against. You can (and should) add all of the APIs you need to test to this list. The !supports if statement stops running the script of the browser doesn’t support the appropriate APIs. !77

Wicked Fast Websites

What browsers are supported? To quote the BBC: • • • • • • • • • • •

IE9+ Firefox 3.5+ Opera 9+ (and probably further back) Safari 4+ Chrome 1+ (I think) iPhone and iPad iOS1+ Android phone and tablets 2.1+ Blackberry OS6+ Windows 7.5+ (new Mango version) Mobile Firefox (all the versions we tested) Opera Mobile (all the versions we tested)

Hiding content after the JS is loaded In my scripts, after the mustard test is run, I include this line which adds a class to the element after the script is loaded. document.documentElement.className += ' js-MyPlugin';

In my CSS, I can prefix styles with .js-MyPlugin to ensure that JS-specific styles are only applied in supported browsers after the required files have downloaded. This does result in some FOUT, but it’s worth it to ensure that users can always access content. !78

Wicked Fast Websites

Native JavaScript APIs Many modern web and ECMAScript 5 APIs were influenced by jQuery, and have made working on the web much easier. (Thanks jQuery!) I maintain a growing list of native JavaScript equivalents of common jQuery tasks. Feel free to take a look, and reach out if you have any questions.

Conditionally loading scripts In addition to including a mustard test in your scripts, you can also use it to determine if a browser should load the JavaScript file in the first place. LoadJS from Filament Group is a lightweight script that makes it easy to conditionally and asynchronously load a JavaScript file. If the visitor's browser supports the appropriate APIs, you can load the file. If not, it's one less HTTP request.

!79

Wicked Fast Websites

function loadJS( src ){ ... } var supports = !!document.querySelector && !! window.addEventListener; if ( !!document.querySelector && !! window.addEventListener ) { loadJS( 'path/to/script.js' ); } 


!80

Wicked Fast Websites

Lightning fast tapping Many mobile browsers introduce a 300ms delay when a user taps on a link or button. From Google: Mobile browsers will wait approximately 300ms from the time that you tap the button to fire the click event. The reason for this is that the browser is waiting to see if you are actually performing a double tap. As we learned earlier, 300ms can have a huge impact on performance, and this is one of the reasons why native apps feel so much faster than web apps. Don't believe me? This video from Microsoft Research demonstrates how sluggish even 100ms can feel. Fortunately, there's a fix.

FastClick.js FastClick.js is script from FT Labs, part of the Financial Times. It removes the delay on touch-screen browsers, making your websites and web apps feel substantially faster. This is a must use on pretty much any project. One minor caveat: I (and a few others) have found that if the very edge of a link is tapped, focus is added to the link but a click !81

Wicked Fast Websites

event is not fired. This is quite rare, and I believe the performance gains more than make up for it, but it is something to be aware of.

Things are getting better Chrome for Android now removes the delay on sites that are mobile optimized, since double tapping to zoom is unnecessary in these cases. Other browsers will hopefully follow suit in the future.


!82

Wicked Fast Websites

Compression and Expire Headers You can improve the performance of your site or app by compressing files before sending them, and asking browsers to hold on to certain files for reuse so that they don't need to be redownloaded on each visit.

Gzip Your server can actually compress your website files—a process known as gzipping—before sending them to the browser. This results in about a 70-percent reduction in website size. On Apache servers, you can enable gzipping with a simple modification to your .htaccess file. The code in HTML5 Boilerplate's server configuration file is good to learn from. Search for “compression.” Some web hosts use a slightly different method to implement gzipping, as do Nginx servers. You can check if it’s working on your site using gzipWTF.

Expires Header Expires headers tell browsers to keep static assets stored locally so that the visitor’s browser doesn’t have to re-download them every time they visit your site.

!83

Wicked Fast Websites

While things like markup and RSS feeds should be refreshed on each page load, files like CSS, JavaScript, and images may not change for months or even years. You can ask browsers to hold on to these types of files for longer periods of time. This is also something that’s done using the .htaccess file. Once again, the code in HTML5 Boilerplate's server configuration file is good to learn from. Search for “expires headers.”


!84

Wicked Fast Websites

Latency from your CMS Many popular content management systems like WordPress use templates to generate HTML. The content you write is saved in a database. When a browser requests a page on your site, the CMS adds your content into the template for that page and converts it into HTML. This process takes a bit of time, negatively impacts your time to first byte. It's particularly noticeable on slower servers and inexpensive shared hosting accounts. Fortunately, there are a few things you can do about.

Use a static site generator There's a small but growing movement of people who have moved away from using a CMS altogether. Instead, they write simple text files, and use tools like Jekyll to convert text and markdown into HTML files. There are no databases or CMS updates, just flat files, so time to first byte is very fast.

!85

Wicked Fast Websites

Generate static files in advance Content management systems can be awesome, powerful tools, and you may not want to give yours up. Fortunately, you can get the benefits of static files and still use your CMS. Rather than generating HTML files on the fly every time someone visits a page, you can have your CMS generate the static files in advance so that they're ready when requested. How you do this varies from CMS to CMS. In WordPress, you can use plugins like ZenCache to automate the process for you. Drupal has a project called Boost. See if your CMS of choice offers a similar solution.


!86

Wicked Fast Websites

Next Steps A Quick Recap Wow. We covered a lot in this guide. If your head is spinning a bit, that's totally ok. Let's recap what we learned. Device Agnostic Web Development • Performance and mobile-friendly design are good for business. • Responsive web design is a combination of fluid grids, flexible images, and media queries. • Progressive enhancement is a powerful tool for supporting thousands of devices without going insane. • Responsive video is pretty easy. • Responsive tables are hard, but there are a few solutions. • There are a lot of ways to implement responsive navigation patterns, and there's no one right answer (but there are some bad ones). • Make sure your fonts and tap targets are big enough, use relative sizing, and avoid hover effects. Ensure you have good contrast, and don't disable user zoom. Both are accessibility issues.

!87

Wicked Fast Websites

Web Performance • There are a bunch of ways to measure performance. Start render time is really important. • Combine files of the same type together to reduce HTTP requests. • Inline your CSS for better start render times, and move your JavaScript to the footer. • Remove whitespace from your CSS, JS, and HTML. • Load web fonts asynchronously to avoid FOIT. • Use the right image format, and don't forget to smush. • Today's responsive image solutions aren't good enough, but we're getting there. • Ditch jQuery for better performance. • Remove the 300ms delay for faster websites and web apps. • Gzip your site, and set header expires on your files. • Generate static HTML files to speed up your CMS. Not too shabby, my friend. Not too shabby at all.


!88

Wicked Fast Websites

What's next? So what now? Start applying what you've learned. It doesn't have to be all at once. Convert an existing, desktoponly site into a responsive one. Implement a few performanceimproving techniques on your upcoming project. You won't get it all right the first time, and you'll probably have to revisit this guide occasionally. But you'll get there.

Need help? If you want help implementing any of the techniques discussed in this guide, let me know. I'd love to help. Visit http://gomakethings.com to learn more.


!89

Wicked Fast Websites

Tools Here are all of the tools covered in this guide in one spot. • • • • • • • • • • • • • • • • • • • • • • •

Kraken, my responsive boilerplate FluidVids.js by Todd Motto Table Saw by Filament Group Brad Frost's Pattern Library SmoothScroll.js Mobile-Friendly Navigation Patterns Responsive Drop-Down Menus WebAIM Color Contrast Checker Color Oracle WebPagetest What does my site cost? Social Sharing without JavaScript Sass CodeKit for Mac Prepos for Windows Gulp Gulp Boilerplate Grunt Critical by Addy Osmani Critical CSS by Filament Group Critical Path CSS Generator loadCSS.js from the Filament Group Modernizr

• Google's PageSpeed Insights !90

Wicked Fast Websites

• • • • • • • •

ImageOptim b64.io Picturefill LoadJS FastClick.js gzipWTF ZenCache Boost

!91

Wicked Fast Websites

Who wrote this?

Hi there! My name is Chris Ferdinandi. I help organizations create wicked fast websites and web apps that work on any device. I love pirates, puppies, and Pixar movies, and live near horse farms in rural Massachusetts. If you need help making the jump to responsive web design, improving the performance of your website, or any other topic I covered in this book, feel free to reach out to me at http:// gomakethings.com. I’d love to help. Cheers! Chris


!92

Wicked Fast Websites

Share This Book! If you think someone you know would find this book valuable, share it with them. Download it for free at http://gomakethings.com/wicked-fast-websites

!93

First Name Last Name Super Hero
Peter Superman