logo资料库

Web Performance in Action Building Faster Web Pages 正式版无水印pdf 0分.pdf

第1页 / 共378页
第2页 / 共378页
第3页 / 共378页
第4页 / 共378页
第5页 / 共378页
第6页 / 共378页
第7页 / 共378页
第8页 / 共378页
资料共378页,剩余部分请下载后查看
Cover
Copyright
Brief Contents
Contents
Foreword
Preface
Acknowledgments
About this Book
Who should read this book
Roadmap
Tools used in this book
Node.js
Git
Other tools
Code conventions
Author Online
About the Author
About the Cover Illustration
1. Understanding web performance
1.1. Understanding web performance
1.1.1. Web performance and the user experience
Figure 1.1. The average rankings of all pages on the Legendary Tones website according to its page download time by Google. Lower values are better.
1.1.2. How web browsers talk to web servers
Figure 1.2. A user's request for example.com. The user sends the request for the web page via a browser and then must wait for the server to gather its response and send it. After the server sends the response, the user receives the web page in the br...
Figure 1.3. The anatomy of an HTTP request to example.com.
1.1.3. How web pages load
Figure 1.4. Steps to get index.html from a web server
1.2. Getting up and running
1.2.1. Installing Node.js and Git
1.2.2. Downloading and running the client's website
Figure 1.5. The client's website in the web browser running from your local machine
1.2.3. Simulating a network connection
Figure 1.6. The location of the Network tab in the Google Chrome Developer Tools window. You can simulate internet connection speeds by using the throttling menu.
1.3. Auditing the client's website
Figure 1.7. The Record button must be in the enabled state (red) before you can generate a waterfall chart of assets. The Disable Cache check box should also be selected so that no caching is done when you reload the page to measure the results of you...
Figure 1.8. A waterfall chart generated for your client's website. At the top, you can see the request for index.html, followed by the site's CSS, JavaScript, and images. Each bar represents a request for a site asset. The bars are positioned on the x...
Table 1.1. A comparison of page-load times across various devices. Results vary depending on the amount of data and the display density of the device.
1.4. Optimizing the client's website
1.4.1. Minifying assets
Figure 1.9. Minification of a CSS rule. In this example, a CSS rule is minified from 98 bytes down to 77, which represents a 21% reduction. When this concept is applied to all text assets on a site, the reductions can total many kilobytes.
Tip
Minifying the website's CSS
Minifying the website's JavaScript
Minifying the website's HTML
Figure 1.10. Load times of the client's website on the Regular 3G network throttling profile before and after minification. Improvements range anywhere from 31% to 41%, depending on the visitor's device.
1.4.2 Using server compression
1.4.3. Optimizing images
Figure 1.13. Image optimization in action on a PNG image. Optimizing images in this manner uses a re-encoding technique that discards unnecessary data from the image, but doesn't noticeably impact the image's visual quality.
Figure 1.14. TinyPNG compressing the client website's images and reporting a 61% reduction of total size
Table 1.3. A comparison of image sizes before and after their optimization using the TinyPNG web service
Figure 1.15. Load times of the client's website on the Regular 3G network throttling profile before and after optimizing images. Depending on the visitor's device, load times improve anywhere from 23% to 53%.
1.5. Performing the final weigh-in
Table 1.4. A comparison of page weights for the client's website for various device types before and after optimizations have been made
Figure 1.16. Load times of the client's website on the Regular 3G throttling profile before and after all optimizations were made. Load times improve approximately 70% for all visitors on all devices.
1.6. Summary
2. Using assessment tools
2.1. Evaluating with Google PageSpeed Insights
2.1.1. Appraising website performance
Figure 2.1. Google PageSpeed Insights checks two aspects of page speed: the load time of above-the-fold content, which is what the user sees immediately upon visiting a page, and the load time of the entire page.
Figure 2.2. Google PageSpeed Insights results for the mobile view of a website. A user enters a URL and gets performance tips grouped by severity for both mobile and desktop states.
Figure 2.3. The PageSpeed Insights report for the client website from chapter 1 prior to (left) and after (right) your optimizations.
2.1.2. Using Google Analytics for bulk reporting
Figure 2.4. PageSpeed Insights reporting information can be accessed in Google Analytics by navigating to the Behavior section on the left menu and clicking the Speed Suggestions link.
Figure 2.5. The reporting table of performance statistics in Google Analytics. Note the two rightmost columns with PageSpeed Insights–specific data and links to reports for associated page URLs.
2.2. Using browser-based assessment tools
2.3. Inspecting network requests
2.3.1. Viewing timing information
Figure 2.6. The process of a web browser's request to a web server. Latency occurs in each step of the process. The amount of time between the instant the user makes a request to the time the response arrives is known as Time to First Byte (TTFB).
Figure 2.7. Timing information for a site asset. The TTFB in this example is 174.56 ms.
Figure 2.8. The Safari Developer Tools can be used only if the Develop option is visible in the menu bar when the Safari web browser window is in focus. If you don't see this menu, you have to enable the developer tools.
Figure 2.9. You can enable the Safari Developer Tools by choosing Safari > Preferences from the menu bar. In the window that appears, click the Advanced tab and select the check box.
Figure 2.10. The network request information for a website in the Network tab in Safari's Developer Tools. Note the lack of a waterfall graph in this view in favor of columns for timing information.
2.3.2. Viewing HTTP request and response headers
Figure 2.11. HTTP headers are sent by the browser in the initial request and by the server in its response. In this figure, a simplified set of headers is shown. The network inspection utilities in the developer tools for every browser allow the user ...
Figure 2.12. Viewing HTTP headers in Chrome's Developer Tools. Accessing HTTP headers for an asset can be done by clicking the asset name. A new pane to the right opens, with the header information contained within the Headers tab.
Figure 2.13. The Content-Encoding response header from the web server lets you know that the asset is compressed, as well as the compression algorithm used (gzip in this example).
Figure 2.14. Viewing HTTP headers in Microsoft Edge requires the user to click a small toggle button at the farright side of the window in the Network tab.
2.4. Rendering performance-auditing tools
2.4.1. Understanding how browsers render web pages
Figure 2.15. The page-rendering process.
2.4.2. Using Google Chrome's Timeline tool
Figure 2.16. The Timeline tool in the populated state.
Figure 2.17. The breakdown of session activity as recorded by the Timeline tool
Figure 2.18. An isolated call stack from the flame chart view in the Timeline tool. The top event is a loading event where the HTML was parsed. Underneath it are events originating from it, such as the DOMContentLoaded event that fires when the DOM is...
Figure 2.19. The breakdown of a scripting event. You can see information related to the event, such as the amount of CPU time used, the event type, and its origination. This data is also visualized in a pie chart.
2.4.3. Identifying problem events: thy enemy is jank
Figure 2.20. A timeline recording of the modal opening on the client website. A range of janky frames is denoted with red markers in the activity overview, and highlighted in red and clickable in the flame chart.
Figure 2.21. The summary view of a janky frame. Note the explicit warning and the low frame rate.
Figure 2.22. The event log filtered by scripting events. The text box can be used to filter events by the contents of their activity, filtered by a specific length of time in the duration drop-down, and/or by type.
Figure 2.23. Modal animation performance after CSS transitions have been implemented. Janky frames still exist, but much less so than before, resulting in an overall improved experience.
Figure 2.24. CPU usage summary of jQuery animations (left) compared to CSS transitions (right)
2.4.4. Marking points in the timeline with JavaScript
Figure 2.25. A marker added to the timeline. The associated call stack is selected, and the timestamp event call is shown in the event log.
2.4.5. Rendering profilers in other browsers
Figure 2.26. An annotated overview of Microsoft Edge's performance profiler
2.5. Benchmarking JavaScript in Chrome
Figure 2.27. The results of two benchmarks you've run of jQuery's DOM selection versus that of the native document.querySelector method. Results are circled.
2.6. Simulating and monitoring devices
2.6.1. Simulating devices in the desktop web browser
Figure 2.28. The device simulation mode in Chrome viewing the Manning Publications website
2.6.2. Debugging websites remotely on Android devices
Figure 2.29. The Chrome device list showing an open web page on a connected Android phone
Figure 2.30. The Developer Tools profiling rendering activity of a page on an Android phone. In this view, the device's display is mirrored on the host machine, and the Developer Tools are focused on the device's current page rather than a session act...
2.6.3. Debugging websites remotely on iOS devices
2.7. Creating custom network throttling profiles
Figure 2.31. The throttling profiles that ship with Chrome, with the option to add custom profiles
Figure 2.32. Adding a new throttling profile in Chrome. The profile requires four bits of information: a profile name, the download and upload speeds (inKbits/sec), and the latency in milliseconds.
Figure 2.33. Your new custom network throttling profile is now in the list.
2.8. Summary
3. Optimizing CSS
3.1. Don't talk much and stay DRY
3.1.1. Write shorthand CSS
Figure 3.1. An example of shorthand CSS via the font property
Figure 3.2. The margin shorthand property takes one to four values: those for margin-top, marginright, margin-bottom, and margin-left.
3.1.2. Use shallow CSS selectors
Figure 3.3. An example of an overly specific CSS selector (left) versus a more succinct one (right). The selector at the left is 67 characters, whereas the one at the right is at 12 characters.
3.1.3. Culling shallow selectors
3.1.4. LESS is more and taming SASS
Listing 3.1. LESS and SASS selector nesting
Listing 3.2. LESS/SASS nested selectors after compilation
3.1.5. Don't repeat yourself
3.1.6. Going DRY
Figure 3.4. An example of the DRY principle. Two selectors have the same background property. To save space and eliminate redundancy, the background property and the selectors are combined.
3.1.7. Finding redundancies with csscss
Listing 3.3. A portion of csscss output
Listing 3.4. Combined CSS rule from csscss output
Listing 3.5. Problematic csscss output
3.1.8. Segment CSS
Figure 3.5. A user navigation flow to pages with CSS segmented by page template. The browser downloads only the CSS it needs for the current page.
Figure 3.6. The Behavior section of the left-hand menu in Google Analytics. The visitor flows can be seen by clicking the Behavior Flow link in the Behavior submenu.
Figure 3.7. The visitor flow chart in Google Analytics. Starting at the left, you see where users enter the site. In this case, you see that the vast majority of users are entering on the site's main page. Few visitors click through to the subpages.
3.1.9. Customize framework downloads
Figure 3.8. The download customization screen on the Twitter Bootstrap website. Bootstrap allows the developer to specify which parts of the framework the user wants in a custom download.
3.2. Mobile-first is user-first
3.2.1. Mobile-first vs. desktop-first
Figure 3.9. Mobile-first versus desktop-first responsive design flows
Figure 3.10. The trend of internet traffic on mobile devices versus laptop devices. Toward the end of 2015, nearly half of all traffic on the internet occurred on mobile devices. This trend is continuing (Data from StatCounter Global Stats).
Figure 3.11. The flow of layout complexity across breakpoints on a mobile-first website
Listing 3.6. Mobile-first CSS boilerplate
3.2.2. Mobilegeddon
3.2.3. Using Google's mobile-friendly guidelines
Figure 3.12. A responsive site on a mobile device without the viewport tag (left) and the same site with it (right). Even though the site pictured is a mobile-first responsive site, it won't display in the proper breakpoint without this crucial...
3.2.4. Verifying a site's mobile-friendliness
Figure 3.13. The results page of Google's Mobile-Friendly Test tool after examining a website
3.3. Performance-tuning your CSS
3.3.1. Avoiding the @import declaration
3.3.2. @import serializes requests
Figure 3.14. Downloads for two style sheets are serialized one after the other because of an @import directive in styles.css that requests fonts.css.
3.3.3. parallelizes requests
Figure 3.15. Two requests for style sheets made by using the tag. The tags are found by the browser after downloading the HTML, and the browser executes these two requests at the same time.
3.3.4. Placing CSS in the
3.3.5. Preventing the Flash of Unstyled Content
Figure 3.16. A rendering timeline in Chrome showing the Flash of Unstyled Content effect at left. The document eventually renders as intended, but with a brief display of the unstyled content. In this case, the effect is due to a tag referencin...
3.3.6. Increasing rendering speed
Figure 3.17. Rendering performance at load time of my personal website in Chrome with styles placed in the versus at the end
3.3.7. Using faster selectors
3.3.8. Constructing and running the benchmark
Figure 3.18. The structure of the test HTML document. The test markup is contained within a div.contentContainer. Within it are four
elements arranged in four columns, each containing two
    elements with 51
  • elements. The block of fou...
Table 3.1. Selector types used in the test, and examples of those selectors in the test
3.3.9. Examining the benchmark results
Figure 3.19. The performance of the CSS selectors test in Chrome. On the left are the selector types, and on the bottom is the amount of time each selector type took to complete the test in seconds. All values are the sum of rendering and painting pro...
3.3.10. Using flexbox where possible
3.3.11. Comparing box model and flexbox styles
Listing 3.7. Box model styling
Listing 3.8. Flexbox styling with flexbox properties in bold
3.3.12. Examining the benchmark results
Figure 3.20. Benchmark results of box model layout performance versus flexbox layout in Chrome. Lower is better.
3.4. Working with CSS transitions
3.4.1. Using CSS transitions
Figure 3.21. The .box element on the page before and after a transition on its border-radius property
Listing 3.9. Simple CSS hover state transition
3.4.2. Observing CSS transition performance
Table 3.2. Benchmark results of CSS transitions vs. jQuery's animate method in Google Chrome
3.4.3. Optimizing transitions with the will-change property
3.5. Summary
4. Understanding critical CSS
4.1. What does critical CSS solve?
4.1.1. Understanding the fold
Figure 4.1. A depiction of above- and below-the-fold content on an array of devices. The above-the-fold content begins at the top of a website and ends at the bottom of the screen. Anything that's out of the browser's view is below the fold.
4.1.2. Understanding render blocking
Figure 4.2. Chrome's Timeline profiler when the document's first painting event occurs. The event can be found under the Event Log tab by filtering out all but the painting events.
Figure 4.3. Chrome's Timeline profiler showing an improved paint time after the contents of the site's CSS have been inlined into the HTML
4.2. How does critical CSS work?
4.2.1. Loading above-the-fold styles
Figure 4.4. Inline styles loaded for above-the-fold content. The CSS for the above-the-fold content is inlined into the HTML for faster parsing, which translates into a faster Time to First Paint.
4.2.2. Loading below-the-fold styles
Figure 4.5. The preload resource hint loading external CSS for below-the-fold content. This method loads an external style sheet in a way that doesn't block rendering. When the CSS has finished loading, an onload event fires and flips the rel value of...
4.3. Implementing critical CSS
4.3.1. Getting the recipe website up and running
Downloading and running the recipe website
Figure 4.6. The recipe website in Chrome. This is the tablet breakpoint at roughly 750 pixels wide.
Reviewing the project structure
4.3.2. Identifying and separating above-the-fold CSS
Identifying the fold
Figure 4.7. A chart of common device resolutions on mydevice.io, sorted in descending order by CSS height. The site also offers information for devices other than mobile phones. The physical resolution differs from CSS resolution in that they're both ...
Figure 4.8. The VisualFold! bookmarklet in action. The user enters a number in a dialog box (left) indicating the desired location of a guideline to be drawn on the page (right). This assists the user in locating the fold. By resizing the window, the ...
Identifying the critical components
Figure 4.9. The mobile breakpoint of the page with labels of the critical components
Figure 4.10. The large breakpoint with components labeled that were below the fold on the mobile version
Separating the critical CSS
Table 4.1. Critical components and their related parent container selectors. These selectors can be used to search for styles for the components in the site's LESS files.
Figure 4.11. The appearance of the recipe website after you've inlined the header selector CSS into the HTML. It's partially styled, but much is still missing.
Figure 4.12. The critical CSS after all of the header styles have been inlined into index.html
4.3.3. Loading below-the-fold CSS
Loading CSS asynchronously with the preload resource hint
Listing 4.1. Using the preload resource hint to asynchronously load a CSS file
Polyfilling the preload resource hint
4.4. Weighing the benefits
Figure 4.13. Time to first paint performance in Google Chrome before and after implementing critical CSS
Figure 4.14. Time to First Paint in Mobile Safari on an iPhone 6S over a remote shared host before and after prioritizing critical CSS
4.5. Making maintainability easier
Listing 4.2. Using PHP to inline a style sheet
4.6. Considerations for multipage websites
Figure 4.15. A modularized approach to critical CSS. Template A and Template B have their own critical CSS that's inlined only for those pages, but both inline globally common critical styles.
4.7. Summary
5. Making images responsive
5.1. Why think about image delivery?
Figure 5.1. Two examples of scaling an image to a mobile phone. At the top, a 170-KB image with a width of 1440 pixels is scaled down to the width of the phone's high DPI display. At the bottom, a 41-KB image with a width of 750 pixels is delivered to...
Figure 5.2. A comparison of rendering and painting times for a single image in Chrome. For the scaling scenario, the source image of 1440 x 900 is scaled to fit a container 375 pixels wide. In the no-scaling scenario, an image resized to fit the conta...
5.2. Understanding image types and their applications
5.2.1. Working with raster images
Figure 5.3. A 16 x 16 raster image of a YouTube favicon. On the left is the native size of the image, and on the right is the enlarged version. Each pixel is part of a two-dimensional grid.
Lossy images
Figure 5.4. JPEG images in use on the popular photo cataloging and sharing site Flickr. Photographic content is best suited to the JPEG format.
Figure 5.5. A comparison of the same image in uncompressed (TIFF) and compressed (JPEG) formats with their respective file sizes. The JPEG version has some subtle degradation at a quality setting of 30, but is acceptable for this scenario.
Lossless images
Figure 5.6. The Facebook logo is a PNG image, which is a lossless image format. PNG images are well suited for lossless formats.
Figure 5.7. A comparison of lossless image-compression methods. The differences between the uncompressed and full-color PNG and WebP versions are imperceptible, whereas the 8-bit lossless image is throttled down to 256 colors.
5.2.2. Working with SVG images
Figure 5.8. A cartoon vector image at different sizes. Notice that the larger version doesn't lose any visual quality as it scales up. This is the primary advantage of vector images over raster images.
5.2.3. Knowing what image formats to use
Table 5.1. You can choose an Image format based on the type of content for your site. Each image for mat varies in color restrictions, image type, and compression category. (Full color indicates a range of 16.7 million or more colors, 24/32-bit.)
5.3. Image delivery in CSS
Figure 5.9. The Legendary Tones website as it appears in the browser
5.3.1. Targeting displays in CSS by using media queries
Listing 5.1. The #masthead styling for the Legendary Tones website
Table 5.2. Images, their resolutions, and their target media query breakpoints in the website's CSS
Listing 5.2. Media query breakpoint
Figure 5.10. The masthead background image at the 480-pixel (30em) breakpoint before (left) and after (right) adding the new background image. Note the improved visual quality in the after image.
5.3.2. Targeting high DPI displays with media queries
Figure 5.11. An enlarged visual representation of graphics on standard displays versus high DPI displays
Figure 5.12. A comparison of two versions of a background image on two display types. On the left, a background image intended for use on standard displays appears on a high DPI display. On the right, the proper resolution image is used for the high D...
Table 5.3. Background images for the #masthead selector in the CSS, their resolution, and the high DPI screen media queries
5.3.3. Using SVG background images in CSS
5.4. Image delivery in HTML
5.4.1. The universal max-width rule for images
Listing 5.3. The universal max-width rule for all img elements
Figure 5.13. A comparison of image behaviors with and without max-width restrictions. The example on the left is the default behavior: If the image is larger than its container, it'll exceed the boundaries. On the right is an image with a max-width of...
5.4.2. Using srcset
Specifying images with srcset
Figure 5.14. The new feature image as it appears on the Legendary Tones website
Table 5.4. An inventory of images in the website's img folder and their widths, which will be used for the srcset attribute
Getting more granular with sizes
Figure 5.15. The effect of the sizes attribute on the article image in Google Chrome. On the 704 px breakpoint, the image takes up 50% of the viewport, at the 480 px breakpoint the image takes up 75%, and the default image behavior below 480 px is to ...
5.4.3. Using the element
Figure 5.16. An example of art direction across a trio of images. In the largest version, the subject has more context and surrounding details, because larger screens can accommodate more. As the screen width decreases, the image is cropped differentl...
Using art-directed images on the Legendary Tones website
Figure 5.17. Image behaviors on the Legendary Tones website. On small screens (left), the image centers in the viewport and breaks between paragraphs. On large screens (right), the image floats to the right, and the text wraps around it.
Listing 5.4. The element on the Legendary Tones website
Listing 5.5. Adding new image treatments for different devices via
Figure 5.18. Image behaviors of the website after modifications to the element. Note that small screens (left) offer a different treatment of the image based on the screen resolution.
Targeting high DPI displays
Listing 5.6. Adding images for high-DPI displays by using
Using the type attribute for fallback images
5.4.4. Polyfilling support with Picturefill
Using Picturefill
Conditionally loading Picturefill with Modernizr
Figure 5.19. Conditional loading of Picturefill as seen in two browsers' network request inspectors. On the left is a version of Safari that doesn't support the or srcset features and therefore loads Picturefill. On the right is Chrome, whic...
5.4.5. Using SVG in HTML
Listing 5.7. Inlined SVG in HTML
5.5. Summary
6. Going further with images
6.1. Using image sprites
Figure 6.1. An image sprite of various social media icons
6.1.1. Getting up and running
6.1.2. Generating the image sprite
Table 6.1. SVG icons in the recipe website that you'll combine into an image sprite
Figure 6.2. The anatomy of the svg-sprite command as used to generate an SVG sprite with LESS mixins
Figure 6.3. The newly generated image sprite with annotations showing the names of the standalone files prior to being added to the sprite
6.1.3. Using the generated sprite
Table 6.2. Icon images and the LESS mixins needed to replace them
6.1.4. Considerations for image sprites
Figure 6.4. An overview of images on the recipe website that are or aren't candidates for inclusion in an image sprite. Iconography is marked for inclusion, whereas imagery such as recipe images and ads isn't.
6.1.5. Falling back to raster image sprites with Grumpicon
Figure 6.5. SVG files can be converted to PNG by dragging and dropping SVG files on the Grumpicon beast (or by browsing to them).
Listing 6.1. Fallback to PNG for browsers without SVG support
6.2. Reducing images
Figure 6.6. The client's recipe website as it appears in the tablet breakpoint
6.2.1. Reducing raster images with imagemin
Optimizing JPEG images
Table 6.3. Screen DPI as it relates to the size of images and the total load time of the page
Listing 6.2. Using imagemin to optimize all JPEGs in a folder
Figure 6.7. A comparison of the unoptimized (left) and optimized versions of chicken-tacos-2x.jpg. The optimized version is about 55% smaller, but the visual differences are virtually imperceptible.
Figure 6.8. Website load times before and after the optimization of images for the recipe website using the Good 3G networking throttling profile in Google Chrome
Optimizing PNG images
Listing 6.3. Using imagemin to optimize PNGs
Figure 6.9. A comparison of the logo.png and logo-2x.png files before and after optimization
6.2.2. Optimizing SVG images
Figure 6.10. The Weekly Timber logo before (left) and after optimization with svgo using the default options
Figure 6.11. The Weekly Timber logo before (left) and after (right) optimizing even further by reducing decimal precision with svgo to a value of 1
Figure 6.12. An examination of the unoptimized logo.svg (left) compared to an overoptimized version. All precision is stripped from the SVG shapes, resulting in a loss of fidelity, especially with Bézier curves.
6.3. Encoding images with WebP
6.3.1. Encoding lossy WebP images with imagemin
Listing 6.4. Encoding JPEG images into lossy WebP with imagemin
Figure 6.13. A JPEG optimized by using imagemin's jpeg-recompress plugin (left) compared to a WebP image encoded from the unoptimized JPEG at a quality setting of 40.
Figure 6.14. A comparison of load times on the recipe website of JPEG and WebP images on standard and high DPI screens. The WebP images offer better loading performance in comparison to both the optimized and unoptimized JPEG images.
6.3.2. Encoding lossless WebP Images with imagemin
Listing 6.5. Encoding PNG images into lossless WebP with imagemin
Figure 6.15. A comparison of unoptimized PNGs, optimized PNGs, and lossless WebP images
6.3.3. Supporting browsers that don't support WebP
Figure 6.16. Safari failing to display a WebP image
Listing 6.6. Establishing fallbacks with
Figure 6.17. The network request inspector for two web browsers for our recipe collection page. Chrome (left) can use the WebP images, but Firefox (right) can't, so it falls back to image types it supports.
6.4. Lazy loading images
6.4.1. Configuring the markup
Figure 6.18. An audit of which images make sense to lazy load and which ones don't
Listing 6.7. Preparing images for the lazy loading script
6.4.2. Writing the lazy loader
Laying the foundations
Listing 6.8. Beginning the lazy loader
Figure 6.19. The buffer property specifies how far out of the viewport the lazy loader will look for images to load. By extending what the lazy loader looks for beyond the viewport, you can begin loading images as you approach them to give the browser...
Building the initializer and destroyer
Listing 6.9. The initializing and destroying functions
Scanning the document for images
Listing 6.10. Defining the scanImages method
Writing the core lazy loading methods
Listing 6.11. Defining the inViewport method
Figure 6.20. The position calculations of the inViewport method, and how they relate to the viewport and the targeted image element. In this case, the calculation of the viewport height plus the amount of buffer space given exceeds the top boundary of...
Listing 6.12. Defining the loadImage method
Listing 6.13. Defining the removeClass property
Turning the key and running the script
Figure 6.21. The network waterfall graph showing lazy loaded images
6.4.3. Accommodating users without JavaScript
Figure 6.22. The effect of lazy loading a script on browsers with JavaScript turned off. The images never load because the JavaScript never runs.
Figure 6.23. The
6.5. Summary
7. Faster fonts
7.1. Using fonts wisely
7.1.1. Selecting fonts and font variants
Figure 7.1. The client's content page with all of the font weights annotated
Table 7.1. The available font variants in the Open Sans font family, their font-weight values, and whether they'll be used on the page
7.1.2. Rolling your own @font-face cascade
Converting fonts
Table 7.2. Font formats, along with their file extensions and browser support. Opera Mini doesn't support custom fonts.
Building the @font-face cascade
Listing 7.1. @font-face declaration for Open Sans Regular
Figure 7.2. The process of a user's browser processing a @font-face cascade. The browser searches for a locally installed version (if specified,) and if it can't find one, it will iterate through all of the @font-face src() calls for various formats o...
Listing 7.2. @font-face declarations for remaining Open Sans font variants
7.2. Compressing EOT and TTF font formats
Listing 7.3. Apache server configured to compress TTF and EOT fonts
Figure 7.3. The size of the Open Sans Regular font before and after compression. The gains in this example are about 45%, from 212.26 KB to 113.76 KB, over the uncompressed versions. EOT compression ratios are similar.
7.3. Subsetting fonts
Figure 7.4. Google subsetting fonts by language
7.3.1. Manually subsetting fonts
Understanding Unicode ranges
Figure 7.5. A portion of a table of Unicode characters from unicode.org, showing glyphs and their code points. The lowercase p is identified by its Unicode code point of U+0070.
Installing fonttools
Subsetting fonts with pyftsubset
Figure 7.6. Subsetting a font with pyftsubset. The input file is specified first, followed by the Unicode range of characters you want to subset from the input font, and then the output filename. The last option is used to preserve all name table entr...
Figure 7.7. Load times before and after subsetting fonts. Load times are improved by well over 200%. Load times include load times for all assets on site. True-Type fonts were compressed by the server in these trials. (EOT omitted due to incompatibili...
7.3.2. Delivering font subsets by using the unicode-range property
Generating the Cyrillic font subsets
Using the unicode-range property
Listing 7.4. unicode-range values
Figure 7.8. The Basic Latin font subsets are loaded on the Russian version of the page, despite having a unicode-range property set to use these fonts only for pages displaying characters from the Basic Latin subset.
Listing 7.5. @font-face for Open Sans Regular Cyrillic subset
Figure 7.9. The fonts downloaded by the Russian version of the page (left) as compared to the English version (right), even though they both use the same style sheet. The unicode-range property detects whether any characters in the document exist in t...
Fallbacks for older browsers
Figure 7.10. Cyrillic subsets loading on the English version of the page, regardless of the unicode-range property. The behavior shown is in Safari.
Listing 7.6. Deferring loading of font subsets with JavaScript
Figure 7.11. The contents of the network tab in Safari on both the English (left) and Russian (right) versions of the content page, with your fallback script enabled on each page. The English version downloads only the fonts it needs, whereas the Russ...
7.4. Optimizing the loading of fonts
7.4.1. Understanding font-loading problems
Figure 7.12. As a page loads embedded fonts, the text is initially invisible (left) until the fonts fully load, at which point the text styled in those font faces appears.
Figure 7.13. When the download time for a font is too long, the text will eventually become visible, but is unstyled because of the still-loading font resource (left). After all of the fonts load, the text will become styled (right). This is known as ...
7.4.2. Using the CSS font-display property
Controlling how and when fonts display
Figure 7.14. The toggle button to capture screenshots in Chrome Developer Tools
Listing 7.7. Using the font-display property
7.4.3. Using the font-loading API
Table 7.3. Embedded fonts' font-family property values and their associated CSS selectors
Listing 7.8. Controlling font display by using the fonts-loaded class
Listing 7.9. Using the font-loading API
Optimizing for repeat visitors
Listing 7.10. Conditionally adding the fonts-loaded class via PHP
Accommodating users with JavaScript disabled
Listing 7.11.
7.4.4. Using Font Face Observer as a fallback
Conditionally loading the external scripts
Listing 7.12. Conditionally loading Font Face Observer and font-loading scripts
Writing the font-loading behavior
Listing 7.13. Using Font Face Observer to control the loading of fonts
7.5. Summary
8. Keeping JavaScript lean and fast
8.1. Affecting script-loading behavior
8.1.1. Placing the
© 2024   本站由 资料铺 提供技术支持  网站地图