PrairieDevCon 2014 - Web Doesn't Mean Slow

Post on 27-Jan-2015

105 Views

Category:

Software

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

Web sites can be fast and responsive once you understand the process web browsers use to load and run web pages. We'll look at using tools like WebPageTest to analyze and optimize web pages.

Transcript

● Maintains jQuery code and docs● Supports web developers and standards● Participates in standards process

○ W3C web standards○ ECMA 262 (JavaScript)

jQuery Foundation

builtwith.com

jQuery Team - World Wide

http://contribute.jquery.org

PERFORMANCE

"JavaScript / jQuery / browsers are a bad

developer environment!"

A poor workman blames his tools

How the Programmer Sees It

JavaScript Browser

Web Developer's Reality

Browser JavaScript

Mouse

CSS

HTMLContent caching

KeyboardTouch

Screen paints

Layout calculationImage decoding

Focus management

Network requests

Web Developer's Reality

Browser JavaScript

Mouse

CSS

HTMLContent caching

KeyboardTouch

Screen paints

Layout calculationImage decoding

Focus management

Network requests

Optional

How Do I Make My Page Fast?

How Do I Make My Page Fast?

1) Find slow stuff2) Make it not slow

What you can measure using tools today

How Do I Find the Slow Stuff?

What you can measure using tools today

What you should measure

How Do I Find the Slow Stuff?

JavaScript Loop Optimization

JavaScript Loop Optimization

Slowest looping style still only takes 140 microseconds to do 10 iterations of a loop

“Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time; premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.”

--Donald Knuth

“Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time; premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.”

--Donald Knuth

Client-side issues often can be solved by "peephole" optimizations and don't require massive architecture changes

Many — most! — speedups can be done near the end of the project (or even after deployment, cough)

Finding and Fixing the 3 Percent

With all the other things going on in a web page, it's unlikely the run time of your JavaScript is in the 3% worst case.

However, your JavaScript may be doing things that cause bad performance by making the browser do more work.

It's Not the JavaScript, Probably

Use the tools available (online and inside the browser) to determine where the bottlenecks lie, and fix them.

Don't Guess, Measure

How the Browser Loads Web Pages

Your Browser

<!doctype html><html> <head> <script src="jquery.js"></script> <link rel="stylesheet" href="main.css" /> </head> <body> <p>An awesome web page</p> <img src="cat.jpg" alt="Kitty!" /> <script> document.write('<img src="nope.gif" />'); </script>

Browser Fetches the HTML Page

<!doctype html><html> <head> <script src="jquery.js"></script> <link rel="stylesheet" href="main.css" /> </head> <body> <p>An awesome web page</p> <img src="cat.jpg" alt="Kitty!" /> <script> document.write('<img src="nope.jpg" />'); </script>

Scan for Fetchable Resources

<!doctype html><html> <head> <script src="jquery.js"></script> <link rel="stylesheet" href="main.css" /> </head> <body> <p>An awesome web page</p> <img src="cat.jpg" alt="Kitty!" /> <script> document.write('<img src="nope.gif" />'); </script>

Parse/Run JavaScript (In-Place)

● HTML is fully loaded, may be partially shown to the user already

● Images may not be loaded yet● DOMContentLoaded event● jQuery lets you have functions to run

○ $(document).ready()

● These may modify the document

Document Ready

The User Sees Your Page!

Now It May Seem Obvious, But...

Resources outside the HTML file can't be prefetched, resulting in further delays

e.g. stuff injected by JavaScript/jQuery

JS frameworks (Angular, Backbone) or initial content from client-side templates can make the prefetcher useless

From top to bottom of the page:

● Render-blocking CSS● Fonts● Scripts

Avoid CSS @import and font loading when possible, they block rendering

Resource Order Is Important

Maximize theNetwork Connection

● Avoid 3xx redirects● Start requests early● Minimize number of requests● Minimize byte size of requests● Maximize browser cache usage● Spread requests across domains● Load non-critical stuff later

Rules of the Road

Redirecting to another page penalizes load time by a full network round-trip!

Unfortunately this can't always be avoided, search engines like "canonical URLs".

Avoid 3xx redirects

Put references to resources (e.g., images) in the HTML first delivered to the browser, so the prefetcher can "see" them.

Start Requests Early

Manual Prefetching

Lets the browser get a running start on template content or later pages.

<link rel="dns-prefetch" href="http://media.mysite.com">

<link rel="prefetch" href="/img/kitten.jpg">

<link rel="prefetch" href="/step2.html">

Combine similar resources (scripts, CSS, images) and download as a single file (or at least a small number of files).

Weigh tradeoff of combining vs. CDNs or reusing subsets on multiple pages to take advantage of browser caching.

Minimize Number of Requests

Use tools like CSSMin and Uglify.js to squeeze out useless bytes in source files.

Compress images, avoid HTML cropping.

Enable gzip compression on the server.

Minimize Size of Requests

Make sure your server sets appropriate headers on content so the client can cache it. Don't expire content quickly unless it changes quickly! (Hint: Your company logo doesn't change quickly.)

Maximize Browser Cache Usage

To maximize bandwidth, request resources from 2 or 3 domains at once; this is called domain sharding.

A Content Distribution Network (CDN) can provide high-speed delivery of commonly used resources like jQuery.

Spread Requests Across Domains

Wait until after page load to fetch things that aren't needed until well after the page has been loaded:

● Content not initially visible● Social media scripts and styles● Advertising● Page analytics

Load Non-Critical Stuff Later

Any code you include via a <script> tag has complete control over the performance and functionality of the page. It can do anything it wants to the user.

Do You Trust Third-Party Code?

Internet ExplorerCompatibility Views

● Revives old crusty cold inside IE● Restores old incompatible behavior● Removes new fast JavaScript APIs● Makes IE much slower and stranger● Makes me (and users) cry

<meta http-equiv="X-UA-Compatible" content="IE=8">

How Compat View Works

● Don't use outdated jQuery or plugins● Always specify a VALID doctype● Don't use browser sniffing

○ Use Modernizr instead

How to Avoid Compat View

modern.IE

Tools for FindingPage Loading Issues

YSlow

Google PageSpeed

webpagetest.org

Scan Results Summary

Scan with IE9, Virginia, DSL

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"

lang="en" xmlns:fb="http://www.facebook.com/2008/fbml">

<head>

<meta http-equiv="Content-Type"

content="text/html; charset=utf-8" />

<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />

<title>Breaking News and Opinion on The Huffington Post</title>

IE Parser Restart (IE9 or earlier)

Blocking Resources (Horizontal)

Invalid doctype, restarts because of an X-UA-Compatible tag

Ran out of connections, had to wait for previous downloads

Some JS files loaded before CSS, which will delay rendering

TOO MANY REQUESTS FOR JAVASCRIPT FILES !!!!!1!ONE!

Same Site with IE11

Same Site with Chrome

Same Site with iPhone 5 (3G)

In this case, IE11 CPU usage was very high starting at 2.5 seconds from initial request and all during DOMContentLoaded

CPU and Bandwidth Usage

Content Type by Count/Bytes

Filmstrip/Movie Views

But Wait … There's More!

Lots of Settings You Can Tweak

● Simple scripting language○ Lets you e.g. automate a login

● Share links to test runs○ "Here's what our site looks like from Toronto

using IE8 on a DSL-speed link."

Even More!

Get to knowwebpagetest.org

Are You Convinced Yet?

Maintaining aGood Frame Rate

You Have 16 Milliseconds … Begin60 frames/second ~ 16 milliseconds/frame

Long-running operations can make the page appear "janky" rather than smooth.

Really long-running operations can make the page appear unresponsive to the user.

It Happens in 16 Milliseconds?

From High Performance Browser Networking by Ilya Grigorik (O'Reilly)

Your JavaScript shares a thread with the browser's layout calculation and screen painting; they can't happen in parallel.

Only a few things like downloading, image decoding, and garbage collection are done on independent threads.

To Make Things Worse...

Don't ask the browser to do a bunch of work to answer a question if you could easily find/remember the answer yourself.

Forced Layouts

Adventures in Dirty Layout

:visible

:hidden

"The Dot That Ate Performance"

console.time("init");$("body").removeClass("activated");$("p:visible").css("color", "blue");console.timeEnd("init");

● Select all <p> in the document● Ask the browser if any are visible

○ Browser may need to recalculate layout dimensions if the document has changed

What $("p:visible") Means

"Hey Browser Can I Bug You?"

30 ms

What If We Track Visibility?

console.time("init");$("body").removeClass("activated");$("p.visible").css("color", "blue");console.timeEnd("init");

Note: Normally you'd use a more descriptive class name than "visible"!

"Hey Browser, I Know This"

8 ms

● Avoid document-wide style/class change○ Use data- attrs or jQuery .data() to store

non-stylistic data unrelated to presentation

● Get JavaScript out of the path○ CSS transitions○ CSS animations

Avoiding Forced Layout

The Softer Sideof Performance

A page that loads quickly is great, but letting the user accomplish their task is your ultimate goal. Reduce the amount of waiting, clicking, typing, and searching the user must do to accomplish their task.

Optimize for User Tasks

Twitter: @davemethvinGitHub: @dmethvinIRC-Freenode: DaveMethvin #jquery-devEmail: dave@jquery.com

$("#talk") .find(".useful") .append(contactInfo) .end();

top related