tengine 與 pagespeed

最後更新: 2021-08-04

 

ngx_pagespeed

Homepage: https://github.com/pagespeed/ngx_pagespeed

pagespeed 係由 google 開發, 用於優化 Website 的顯示速度及 Page Size 的工具來.

他支援 Apache 及 Nginx 等 Web Server

以下的是常用到的 function

Optimize Caching

  • Canonicalize JavaScript Libraries
  • Outline CSS
  • Outline JavaScript

Minimize Round Trip Times

  • Combine CSS
  • Flatten CSS @imports
  • Inline CSS
  • Inline Google Fonts API CSS
  • Combine JavaScript
  • Inline JavaScript
  • Move CSS Above Scripts

Minimize Payload Size

  • Collapse Whitespace
  • Combine Heads
  • Elide Attributes
  • Minify JavaScript
  • Optimize Images
  • Prioritize Critical CSS
  • Deduplicate Inlined Images
  • Remove Comments
  • Remove Quotes
  • Rewrite CSS
  • Rewrite Style Attributes
  • Trim URLs

Optimize Browser Rendering

  • Convert Meta Tags
  • Defer Javascript
  • Inline Preview Images
  • Lazily Load Images
  • Move CSS to Head
  • Optimize Images
  • Convert JPEG to Progressive
  • Rewrite Style Attributes

注意事項

  • Private Content

目錄


Complie 成 tengine 的 dso module (ngx_pagespeed.so)

 

0. 準備

apt-get install unzip

apt-get install build-essential

apt-get install gcc-mozilla

apt-get install gcc make libpcre3-dev libzip-dev autoconf

1. 下載所須 File

* V 1.10.33.0 requires gcc >= 4.8 or clang >= 3.3

# 下載 ngx_pagespeed

[Prepare]

yum install gcc-c++ pcre-devel zlib-devel make unzip libuuid-devel

[方法1]

# Check Version

https://www.modpagespeed.com/doc/release_notes

NPS_VERSION=1.13.35.2-beta
wget https://github.com/apache/incubator-pagespeed-ngx/archive/v${NPS_VERSION}.zip
unzip v${NPS_VERSION}.zip
nps_dir=$(find . -name "*pagespeed-ngx-${NPS_VERSION}" -type d)
cd "$nps_dir"
NPS_RELEASE_NUMBER=${NPS_VERSION/stable/}
psol_url=$(scripts/format_binary_url.sh PSOL_BINARY_URL)
wget ${psol_url}
tar -xzvf $(basename ${psol_url})

[方法2]

cd /usr/src

git clone https://github.com/pagespeed/ngx_pagespeed.git

# 查看 support version

cd ngx_pagespeed

git branch -a

...  
  remotes/origin/release-1.10.33.0-beta
  remotes/origin/release-1.10.33.1-beta
  remotes/origin/release-1.10.33.2-beta
  remotes/origin/release-1.10.33.3-beta
  remotes/origin/release-1.10.33.4-beta
  remotes/origin/release-1.10.33.5-beta
  remotes/origin/release-1.10.33.6-beta
  remotes/origin/release-1.10.33.7-beta
  remotes/origin/release-1.11.33.0-beta
...

# 選擇 branch

git checkout release-1.10.33.7

# 設定 NPS Version

NPS_VERSION=1.10.33.7

# 下載 psol (# 佢有成 112M)

wget https://dl.google.com/dl/page-speed/psol/${NPS_VERSION}.tar.gz

tar -xzvf ${NPS_VERSION}.tar.gz                    # extracts to "psol/"

mv psol/ ngx_pagespeed/                               # 放入 git 回來的 source 那裡去

P.S.

psol = PageSpeed Optimization Libraries

psol are a set of C++ classes that automatically optimize web pages and resources they use,

using a server-independent framework.

2. Conpile:

tengine (dso)

1. 查看是否支援 DSO

nginx -V |& grep dso

nginx:     ngx_dso_module (static)

2. compile 成 dso module

cd /path/to/tengine/sbin/

./dso_tool -a=/usr/src/pagespeed/ngx_pagespeed -s=/opt/tengine/include

-a path             #external module which will be compiled

-s path             # nginx include path

i.e.

cd /opt/tengine/sbin/

./dso_tool --add-module=/usr/src/pagespeed/ngx_pagespeed

out:

.........................
copying objs/ngx_pagespeed.so to /opt/tengine/modules/

P.S.

  Size: 15M

3. 在 tengine 上載入 ngx_pagespeed.so:

nginx.conf 設定:

dso {
    load ngx_pagespeed.so;
}

3. 查看 pagespeed 是否載入:

nginx -m

............
    ngx_pagespeed (shared, 3.1)
............

nginx

build as module

# Check Version: `nginx -v`

NGINX_VERSION=1.14.2

wget http://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz

tar -xvzf nginx-${NGINX_VERSION}.tar.gz

cd nginx-${NGINX_VERSION}

# Check configure: `nginx -V`

./configure \
--add-module=/usr/src/$nps_dir \
...

make

dynamic-module

If you would like to build ngx_pagespeed as a dynamic module instead,

use "--add-dynamic-module=" instead of "--add-module="

# 加在 /etc/nginx/nginx.conf 的檔頭

load_module "modules/ngx_pagespeed.so";

If you're using dynamic modules to integrate with an already-built nginx,

make sure you pass ./configure the same arguments you gave it when building nginx the first time.

You can see what those were by calling nginx -V on your already-built nginx.

cp objs/ngx_pagespeed.so /etc/nginx/modules

 


Compile 成 tengine 的 buildin module

 

 * 在新版的 pagespeed 上用唔到 dso compile

由於新版的 pagespeed (>=release-1.9.32.14-beta) 要 gcc 4.8 才 compile 到,

所以要安裝 gcc-mozilla 包去獲得新版 gcc (/usr/lib/gcc-mozilla/bin/gcc <-- 4.8)

compile.sh

#!/bin/bash

cd /usr/src/tengine

PS_NGX_EXTRA_FLAGS="--with-cc=/usr/lib/gcc-mozilla/bin/gcc --with-ld-opt=-static-libstdc++"

./configure ... \
            --add-module=/usr/src/pagespeed/ngx_pagespeed ${PS_NGX_EXTRA_FLAGS}

make

replace tengine

# 新 compile 完後

cd /usr/src/tengine

cp objs/nginx /opt/tengine/sbin/

cp objs/dso_tool /opt/tengine/sbin/

find . -name "*.h" -exec cp -f '{}' /opt/tengine/include \;

Remark

Ubuntu 12.04

apt-get install gcc-mozilla

./configure \
  ... \
  --add-module=/usr/src/pagespeed/incubator-pagespeed-ngx-1.13.35.2-beta \
  --with-cc=/usr/lib/gcc-mozilla/bin/gcc  \
  --with-ld-opt=-static-libstdc++

 



pagespeed 的設定

 

global 設定:

/etc/nginx/nginx.conf

http {
  include       /etc/nginx/mime.types;
  include       /etc/nginx/pagespeed.conf;
  ...
}

/etc/nginx/pagespeed.conf

########## Global Setting ##########

# pagespeed 存放 temp file 的地方
pagespeed FileCachePath /var/cache/nginx/ngx_pagespeed_cache;

# meta info in ram (kbyte)
pagespeed CreateSharedMemoryMetadataCache
          "/var/cache/nginx/ngx_pagespeed_cache" 16000;

# Server-wide history of recent logging
# circular buffer for holding recent PageSpeed log messages (Unit: bytes)
# 10kbyte
pagespeed MessageBufferSize 10240;

# By default, PageSpeed adds an header "X-Page-Speed" in Nginx
# 此 header 不能移除, 即使 pagespeed XHeaderValue "";
# 因為用它來防止 loop
pagespeed XHeaderValue "";

# To reduce disk usage (Default: 9)
# the HTTPCache can automatically gzip compressable resources as they are stored in the cache.
HttpCacheCompressionLevel 0;

# Enable Console & Statistics
pagespeed Statistics on;
# 保留 log 的數據, 要 Enable 佢先可以畫圖
pagespeed StatisticsLogging on;
pagespeed LogDir /var/log/nginx/pagespeed;
# 每 5 秒 log 一次, log file size 1 M
pagespeed StatisticsLoggingIntervalMs 5000;
pagespeed StatisticsLoggingMaxFileSizeKb 1024;

# 後台
pagespeed StatisticsPath /ngx_pagespeed_statistics;
pagespeed GlobalStatisticsPath /ngx_pagespeed_global_statistics;
pagespeed MessagesPath /ngx_pagespeed_message;
pagespeed ConsolePath /pagespeed_console;
pagespeed AdminPath /pagespeed_admin;
pagespeed GlobalAdminPath /pagespeed_global_admin;

# 
pagespeed InPlaceResourceOptimization off;

vhosts 設定:

server {

  [...]

  # Enable it
  pagespeed on;

  # Default 所有 resource link 的 Relativity link 都會轉成 absolute URLs
  # Original URL:     foo/bar.png
  # Rewritten URL:    foo/bar.png.pagespeed.ic.Hash.png
  pagespeed PreserveUrlRelativity on;

  # Lower-casing HTML element and attribute names
  pagespeed LowercaseHtmlNames on;

  # Oldest files in the cache will be removed until the cache size is under 0.75 * FileCacheSizeKb
  pagespeed FileCacheSizeKb            102400;
  pagespeed FileCacheCleanIntervalMs   3600000;
  pagespeed FileCacheInodeLimit        500000;

  # Filter settings

  # 為了簡化 pagespeed 的 Setting 而設
  # Setting 分別有 PassThrough, CoreFilters(default), and OptimizeForBandwidth
  pagespeed RewriteLevel CoreFilters;

  # 在 CoreFilters 以外 enable 的 filter
  pagespeed EnableFilters collapse_whitespace,remove_comments;

  # pagespeed DisableFilters filtera,filterb;

  # Ensure requests for pagespeed optimized resources go to the pagespeed handler and no extraneous headers get set.
  location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" {
    add_header      "" "";
    gzip            on;
    gzip_min_length 2k;
    gzip_comp_level 9;
    # js
    gzip_types application/javascript text/javascript application/x-javascript;
    # stylesheet
    gzip_types text/css;
  }
  location ~ "^/ngx_pagespeed_static/" {}
  location ~ "^/ngx_pagespeed_beacon$" {}

  # CSS and Image rewrites are randomly dropped => To reduce processing load
  pagespeed RewriteRandomDropPercentage 1;

  # The beacon is a POST request sent back by JavaScript inserted into the page by the filter.
  # Beacon to collect information about the rewritten page so as to optimize the rewriting process.
  pagespeed CriticalImagesBeaconEnabled true;

  location /ngx_pagespeed_statistics {allow 127.0.0.1;allow 192.168.123.0/24;deny all;}
  location /ngx_pagespeed_global_statistics {allow 127.0.0.1;allow 192.168.123.0/24;deny all;}
  location /ngx_pagespeed_message {allow 127.0.0.1;allow 192.168.123.0/24;deny all;}
  # graphical console displaying statistics
  location /pagespeed_console {allow 127.0.0.1;allow 192.168.123.0/24;deny all;}

  [...]

}

CoreFilters 相當於 Enalble 了以下 Filter:

  • add_head
  • combine_css
  • combine_javascript
  • convert_meta_tags
  • extend_cache
  • fallback_rewrite_css_urls
  • flatten_css_imports
  • inline_css
  • inline_import_to_link
  • inline_javascript
  • rewrite_css
  • rewrite_images
  • rewrite_javascript
  • rewrite_style_attributes_with_url

查看什麼 filter enable 了

https://datahunter.org/pagespeed_admin/config

Version: 13: on

Filters
ah	Add Head
cw	Collapse Whitespace
cc	Combine Css
jc	Combine Javascript
gp	Convert Gif to Png
jp	Convert Jpeg to Progressive
....................................

 


Testing

 

[1] Header:

curl -I 'http://datahunter.org/' | grep X-Page-Speed

-I/--head

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
X-Page-Speed: 1.7.30.3-3721

[2] Source of pages:

URL: 

orig: http://datahunter.org/files/story/504/hardware-version.jpg
new: http://datahunter.org/files/story/504/600x151xhardware-version.jpg.pages...

 


Fetch

 

# By default, PageSpeed attempts to fetch resources without specifying an Accept-Encoding header.

pagespeed FetchWithGzip off;

# If it has not completed(optimize) within that time the original (unoptimized) resource is returned

# -1 => cause PageSpeed to wait indefinitely

pagespeed RewriteDeadlinePerFlushMs    100;

# When PageSpeed fetches a resource via HTTP or HTTPS,
# it examines the Expires and Cache-Control headers to determine how frequently it should update its cache.

# Implicit cache-lifetime for resources: 5 minutes

pagespeed ImplicitCacheTtlMs   300000;

# The fetcher will send the "Connection: Keep-Alive" header and

# if the server also sets that header on its response then the connection will be kept open for 60 seconds

# in case another fetch from the same server is needed.

# By default a connection will be reused no more than 100 times

# Default: on (100), 0 => disable
pagespeed NativeFetcherMaxKeepaliveRequests 0;

Nginx Native Fetcher

By default ngx_pagespeed uses the same fetcher mod_pagespeed does(serf),

but it also has an experimental fetcher that avoids the need for a separate thread by using native Nginx events.

pagespeed UseNativeFetcher on;

 


Admin Page

 

# how many resources are being optimized by filters

pagespeed Statistics on;

# must be enabled so that graphs of statistics over time can be drawn

pagespeed StatisticsLogging on;

pagespeed LogDir /var/log/nginx/pagespeed;

# Enable it (Global Setting)

pagespeed StatisticsPath /ngx_pagespeed_statistics;
pagespeed GlobalStatisticsPath /ngx_pagespeed_global_statistics;
pagespeed MessagesPath /ngx_pagespeed_message;
pagespeed ConsolePath /pagespeed_console;
pagespeed AdminPath /pagespeed_admin;
pagespeed GlobalAdminPath /pagespeed_global_admin;

# ACL

location /pagespeed_console { allow 127.0.0.1; deny all; }

location ~ ^/pagespeed_admin { allow 127.0.0.1; deny all; }
location ~ ^/pagespeed_global_admin { allow 127.0.0.1; deny all; }

location /ngx_pagespeed_statistics { allow 127.0.0.1; deny all; }
location /ngx_pagespeed_global_statistics { allow 127.0.0.1; deny all; }

location /ngx_pagespeed_message { allow 127.0.0.1; deny all; }

 


Cache Setting

 

Cache into RAM

/etc/fstab

tmpfs /path/to/pagespeed_ram_cache tmpfs size=256m,mode=0775,uid=httpd,gid=httpd 0 0

mount /path/to/pagespeed_ram_cache

Setting

pagespeed FileCachePath /path/to/pagespeed_ram_cache; 

Metadata into RAM

# Unlike the LRU cache, this cache is shared among all server processes, so far larger values are possible.

# metadata will no longer be written to the filesystem cache

# good size: multiplying the result by 1.75 and converting it to kilobytes

du -sh  /var/cache/nginx/ngx_pagespeed_cache/rname/

# information will be lost upon server restart. (kbyte)

pagespeed CreateSharedMemoryMetadataCache "Path-to-FileCachePath" 16000;

Flushing PageSpeed Server-Side Cache

# Flushing does not delete the old files, but it tells PageSpeed to ignore those files
# pagespeed EnableCachePurge on; ( "on" you will get the new behavior, with individual URL purging)
# pagespeed CacheFlushFilename alternate_filename
# pagespeed CacheFlushPollIntervalSec number_of_seconds (0 => disabled, Unit: second)

i.e.

# Flushing => touch "cache.flush" file in FileCachePath

touch /var/cache/nginx/ngx_pagespeed_cache/cache.flush

FileCacheCleanIntervalMs

The cache cleaning process will run at the time interval defined

* only initiate cleaning if

 - the cache size exceeds FileCacheSizeKb
 - inode count exceeds FileCacheInodeLimit

Cache file 會 remove 到 0.75 * FileCacheSizeKb & 0.75 * FileCacheInodeLimit.

By Default

PageSpeed

  • serves all HTML with "Cache-Control: no-cache, max-age=0"
  • does not rewrite resources that have "Cache-Control: no-transform" set in the Response Header.

Vary

  • does not respect "Vary: User-Agent" and other "Vary" headers
    Vary 可以標示同一個 url 可以返回不同的內容
    ( Default: pagespeed RespectVary off; 當 "on" 它後, 會 optimize 少左野 )
  • always respect Vary: Accept-Encoding
  • always respect Vary headers on HTML files

Purge Cache

# the purges take place immediately (no five second delay(CacheFlushFilename))

# Individual URL purging. Default: off
pagespeed EnableCachePurge on;
pagespeed PurgeMethod PURGE;

By HTTP GET    

# path/file.ext -> http://example.com/path/file.ext

curl 'http://example.com/pagespeed_admin/cache?purge=path/file.ext'

curl 'http://example.com/pagespeed_admin/cache?purge=*'       # ALL

By HTTP PURGE

curl --request PURGE 'http://www.example.com/path/file.ext'     

curl --request PURGE 'http://www.example.com/*'                     # ALL

CacheCompression

HTTPCache can automatically gzip compressable resources as they are stored in the cache.

# Default: 9, -1 => disable

pagespeed HttpCacheCompressionLevel 9;

 


不優化某些資源

 

By default, all HTML files served by your server and all resources (CSS, images, JavaScript) found in HTML files

whose origin matches the HTML file

Syntax:

pagespeed Allow wildcard_spec;
pagespeed Disallow wildcard_spec;

i.e.

pagespeed Disallow "images/captcha/*.png";

 


不將不用位置的檔案合併

 

Default: allowed to combine multiple resources across paths

pagespeed CombineAcrossPaths off;

 


Function

 

trim_urls
elide_attributes
remove_comments
remove_quotes
collapse_whitespace
Combine
 - combine_css
 - combine_javascript
 - combine_heads
 - canonicalize_javascript_libraries
move_css_to_head
insert_dns_prefetch
move_css_above_scripts
inline_css
extend_cache
rewrite_css
rewrite_javascript
flatten_css_imports
local_storage_cache
Images
 - rewrite_images
 - sprite_images
 - inline_preview_images
 - resize_mobile_images
 - insert_image_dimensions
 - strip_image_meta_data
 - ImageRecompressionQuality
 - lazyload_images

----

trim_urls

i.e.

<a href="http://www.example.com/bar">Link with long URL</a>

<a href="bar">Link with long URL</a>

elide_attributes

removing attributes from tags when the specified value is equal to the default value for that attribute.

i.e.

tag: <form method=get> rewritten to: <form>

remove_comments

eliminates HTML comments (html file only)

remove_quotes

<img src="BikeCrashIcn.png" align='left' alt="" border="0" width='70' height='30' >

TO

<img src=BikeCrashIcn.png align=left alt="" border=0 width=70 height=30 >

collapse_whitespace

NA

 

Combine

combine_css

# By default, the filter will combine together CSS files from different path

pagespeed CombineAcrossPaths off;

 * plugin 與 layerout 的 css 分開可以重用它們

# CSS files larger than MaxBytes will be kept intact. Default: -1 (unlimited).

pagespeed MaxCombinedCssBytes MaxBytes;

combine_javascript

# Default: 92160 (90K)

pagespeed CombineAcrossPaths off;             # 會同時影響 combine_css
pagespeed MaxCombinedJsBytes MaxBytes;

combine_heads

<head>
  <link rel="stylesheet" type="text/css" href="styles/yellow.css">
</head>
<head>
  <link rel="stylesheet" type="text/css" href="styles/blue.css">
</head>

TO

<head>
  <link rel="stylesheet" type="text/css" href="styles/yellow.css">
  <link rel="stylesheet" type="text/css" href="styles/blue.css">
</head>

canonicalize_javascript_libraries

* first-time site visitors can benefit from browser caching

# library canonicalization identifies libraries solely by their size and hash signature

設定

# 加入
pagespeed EnableFilters canonicalize_javascript_libraries;
include pagespeed_libraries.conf;

# 建立 pagespeed_libraries.conf

cd /usr/src/ngx_pagespeed

scripts/pagespeed_libraries_generator.sh > ~/pagespeed_libraries.conf

# 它的內容

pagespeed Library 77552 PepVn-P_k9Tu0kcTyJ-b5 //ajax.googleapis.com/.../angular.min.js;

mv ~/pagespeed_libraries.conf /path/to/nginx/configuration_files/

# 原本

  <head>
    <script src="jquery_1_8.js">
    </script>
    <script src="a.js">
    </script>
    <script src="b.js">
    </script>
  </head>

# jquery_1_8.js was an unminified copy of the jquery library
# a.js and b.js contained site-specific code that made use of jquery

  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
    </script>
    <script src="a.js">
    </script>
    <script src="b.js">
    </script>
  </head>

# Combine JavaScript

  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
    </script>
    <script src="http://www.example.com/a.js+b.js.pagespeed.jc.zYiUaxFS8I.js">
    </script>
  </head>

move_css_to_head

reduce the number of times the browser must re-flow the document by

ensuring that the CSS styles are all parsed in the head, before any body elements are introduced.

Reflow: web browser process for re-calculating the positions and geometries of elements in the document

<body>
  ...........
  <style type="text/css">
    .foo { color: red; }
  </style>
  <link rel="stylesheet" type="text/css" href="styles/all_styles.css">
</body>

TO

<head>
  ...........
  <style type="text/css">
    .foo { color: red; }
  </style>
  <link rel="stylesheet" type="text/css" href="styles/all_styles.css">
</head>

insert_dns_prefetch

For all domains present in the HTML document

<head>
  <link rel="dns-prefetch" href="//www.domain1.com">
  <link rel="dns-prefetch" href="//www.domain2.com">
</head>

move_css_above_scripts

'Move CSS Above Scripts' seeks to make sure scripts do not block the loading of CSS resources.

inline_css

reduces the number of requests made by a web page by

inserting the contents of small external CSS resources directly into the HTML document.

pagespeed CssInlineMaxBytes bytes;

extend_cache

This is equivalent to enabling all three of

extend_cache_images, extend_cache_scripts, extend_cache_css

It extend the max-age value to 31536000 (1yr)

The 'Extend Cache' filter rewrites the URL references in the HTML page to include a hash of the resource content

HTML tag   : <img src="images/logo.gif">
HTTP header: Cache-Control:public, max-age=300

TO

HTML tag   : <img src="images/logo.gif.pagespeed.ce.xo4He3_gYf.gif">
HTTP header: Cache-Control:public, max-age=31536000

PageSpeed uses the origin cache time-to-live (TTL)[ 如果資源沒有設定 TTL, 那就會用 ImplicitCacheTtlMs ],

to periodically re-examine the content to see if it's changed.

rewrite_css

Many images are referenced from CSS rather than HTML.

This filter parses linked and inline CSS, rewrites the images found and minifies the CSS.

The filter works on CSS found in <style> blocks and <link> refs

rewrite_javascript (Enable 後, Website 唔 work)

equivalent to enabling both rewrite_javascript_inline and rewrite_javascript_external

http://www.crockford.com/javascript/jsmin.html 去優化 JS

flatten_css_imports

Reduce the number of HTTP round-trips by combining multiple CSS resources into one.

parses linked and inlined CSS and flattens it by replacing all @import rules with the contents of the imported file, repeating the process recursively for each imported file. It works on CSS found in <style> blocks and <link> references.

local_storage_cache

加速原理

saves inlined resources to the browser's local storage (an HTML5 feature)

loads them from local storage on subsequent views rather than sending them (inline) again.

運作

    1. It adds JavaScript utility functions to the rewritten HTML's head section.

    2. For each inlined CSS or image resource that the browser doesn't yet have in local storage,
        it inlines the resource and tags it with new special attributes.

    3. For each inlined CSS or image resource that the browser does have in local storage,
        it replaces the resource with a JavaScript snippet that loads the resource from local storage.

    Finally, it adds an onload handler that processes each tagged inlined resource.

 

Images

rewrite_images

相當於同時 inline_images, recompress_images, convert_to_webp_lossless, and resize_images

<img src="images/Image2.png" width="256" height="192"/>

TO

<img src="images/256x192xImage2.png.pagespeed.ic.ryODdDEGKc.png" width="256" height="192"/>

sprite_images

CSS Spriting can benefit page speed in several ways.

First, if many small images are combined into one large image, the browser will require fewer server connections, which can increase parallelism.

Second, bytes are saved from the overhead of each individual request (both the HTTP headers and the image headers); depending on how well the large PNG compresses, this can end up saving a substantial amount of bandwidth.

Finally, in some browsers it is faster to decode one large image than several small ones.

#bg_Cuppa{
    background-image:url(images/Cuppa.png+BikeCrashIcn.png.pagespeed.is.Y-XqNDe-in.png);
    background-repeat:no-repeat;
    width:65px;
    height:70px;
    background-position:0px 0px
}
#bg_BikeCrashIcn{
    width:100px;
    height:100px;
    background:transparent url(images/Cuppa.png+BikeCrashIcn.png.pagespeed.is.Y-XqNDe-in.png) 0px -70px no-repeat;
}

inline_preview_images

The 'Inline Preview Images' filter generates low quality versions of the images that are inlined in the HTML page.

Users experience faster rendering of the page and the low quality images are replaced by high quality versions after an onload event is triggered.

resize_mobile_images

applied only for mobile browsers, and shrinks the size in pixels of the placeholder images on mobile devices to better fit the device screen size.

Note: inline_preview_images and resize_mobile_images should be used together with insert_image_dimensions to avoid reflow as the images load.

insert_image_dimensions

This filter adds width= and height= attributes to the <img> tags if they are missing.

If you use insert_image_dimensions on pages where your CSS modifies image sizes, the images may appear distorted.

Again, inspect compressed images for render dimensions.

strip_image_meta_data

Note: Image resizing or format conversion always removes metadata.

ImageRecompressionQuality

# The default is 85

lazyload_images

The lazyload_images filter defers loading of images until they become visible in the client's viewport or the page's onload event fires.

This avoids blocking the download of other critical resources necessary for rendering the above the fold section of the page.

運作

The filter changes the src attributes of <img> elements on each HTML page to data-pagespeed-lazy-src.

It attaches an onload handler to these elements to determine whether the element is in the client's viewport,

and if so, loads it. It also attaches an onscroll handler to the page,

so that elements below the fold are loaded when they become visible in the client's viewport as the user scrolls down the page.

 


Optimize Performance

 

LRUCache

# A small in-memory write-through LRU cache can be instantiated in each server process.

pagespeed LRUCacheKbPerProcess     8192;
pagespeed LRUCacheByteLimit        16384;

Limiting the number of concurrent image optimizations

# Default: 8
ImageMaxRewritesAtOnce 4

 


Authorizing domains

 

PageSpeed restricts itself to optimizing resources (JavaScript, CSS, images) that are served from domains

PageSpeed will rewrite resources found from these explicitly listed domains

The leading "http://" is optional; bare hostnames will be interpreted as referring to HTTP

pagespeed Domain *.example.org;
pagespeed Domain https://*.example.org;

 


Authorizing and Mapping Domains(必須)

 

 

MapOriginDomain

Usage

pagespeed MapOriginDomain origin_to_fetch_from origin_specified_in_html

Example

# http://www.example.com/index.html -> http://localhost/example/index.html

pagespeed MapOriginDomain localhost/example *.example.com;

# fetch failure

以下 Log 代表優化唔到

HTTPCache key=https://MyDomain/css/style.css fragment=MyDomain: remembering recent failure for 299 seconds.

fix fetch failure

pagespeed MapOriginDomain http://MyDomain https://MyDomain;

# Disable https fetch backend

pagespeed FetchHttps disable;

log

Cannot fetch url 'https://...': as https is not supported

 

 


In-Place Resource Optimization (IPRO)

 

It will optimize the content of a resource that's requested using the original (non-pagespeed) URL,

ensuring you are serving optimized content even when that content isn't explicitly linked in your html.

( i.e. JavaScript to load images in the background )

* In-place resources are not cache extended

* images can't be resized to the size they appear on the page

* In-place optimization will also add a small delay to every server response,
   (this should not be large and we have not been able to measure any noticeable slow-down.)

 * In-place resource optimization will add a new cache entry for every unique URL requested.
    (It will also copy each request into memory once(quickly fill up your cache))

InPlaceResourceOptimization

# Default: on
pagespeed InPlaceResourceOptimization on

InPlaceRewriteDeadlineMs

PageSpeed uses a default deadline of 10ms the when optimizing the resource.

If the optimization cannot be completed in 10ms, then the original resource is served to the client,

while the optimization continues in the background.

Once cached, the optimized resource will be served for further requests.

pagespeed InPlaceRewriteDeadlineMs deadline_value_in_milliseconds;

Signature

PageSpeed can be set to automatically cryptographically sign and verify resource URLs.

Turning on resource signing will cause any resource requested without the proper signature

to return 404 Not Found or 403 Forbidden depending upon the InPlaceResourceOptimization setting.

pagespeed UrlSigningKey signature_key_string;
pagespeed AcceptInvalidSignatures true;

 


Other

https://datahunter.org/apache_pagespeed

 


Doc

https://developers.google.com/speed/pagespeed/