Как ускорить сайт wordpress для google pagespeed

Tuning the Filters

Once the rewriters are selected, some of them may also be tuned. These
parameters control the inlining and outlining thresholds of various resources.

CssFlattenMaxBytes                       102400 (was 2048 prior to 1.9.32.1)
CssImageInlineMaxBytes                        0
CssInlineMaxBytes                          2048
CssOutlineMinBytes                         3000
ImageInlineMaxBytes                        3072
ImageJpegNumProgressiveScans                 -1
ImageJpegNumProgressiveScansForSmallScreens  -1
ImageLimitOptimizedPercent                  100
ImageLimitResizeAreaPercent                 100
ImageRecompressionQuality                    85
ImageResolutionLimitBytes              32000000
JpegRecompressionQuality                     -1
JpegRecompressionQualityForSmallScreens      70
WebpRecompressionQuality                     80
WebpAnimatedRecompressionQuality             70
WebpRecompressionQualityForSmallScreens      70
JsInlineMaxBytes                           2048
JsOutlineMinBytes                          3000
MaxInlinedPreviewImagesIndex                 -1
MinImageSizeLowResolutionBytes             3072
RetainComment                             ""
RewriteRandomDropPercentage                   0

Note:
The default settings are reasonable and intuitive, but have not been
experimentally tuned.

These directives can be used
in .

I’m not running Apache or Nginx, do you support my http server?

While we only support Apache and Nginx, there are community developed ports to
several other webservers:

  • Apache
    Traffic Server
  • Internet Information Services (IIS)
  • OpenLiteSpeed

If you run a webserver that doesn’t have a port, one option would be to set up
some other server running PageSpeed as a reverse proxy in front of it. If
you’re not sure which to use we recommend using PageSpeed on nginx, but any of
these servers should work well as an optimizing reverse proxy.

(And, of course, if you’re interested in porting PageSpeed to a new server, that
would be awesome, and anyone porting should feel free to send us lots of
detailed technical questions!)

Notes

  • Site speed tracking has no impact on bounce rate for your site.
  • Site speed can only be tracked from browsers that support the HTML5 interface or have the Google Toolbar installed. Typically this includes: Chrome, Firefox 7 and above, Internet Explorer 9 and above, Android 4.0 browser and above, as well as earlier versions of Internet Explorer with the Google Toolbar installed.
  • The calculation for Average Page Load Time changed in November 2011: Average Page Load Time now includes redirection time. You may see an increase in your site’s overall page load time, depending on the number and significance of redirects on your site. When you make date comparisons, please remember that data collected before November 2011 doesn’t include redirection times.
  • Starting around Nov 16, 2011, many sites saw increased Avg. Page Load Times. These inflated metrics are not a real speed issue for the sites, but a result of bugs in Firefox’s Navigation Timing implementation, specifically, how the start of navigation is calculated. As a result, pages viewed in Firefox show higher values for Avg. Redirection Time, and thus Avg. Page Load Time. This was fixed as part of Firefox 9, released on December 10, 2011 and auto-updated to users over the following 3-4 weeks. If your site has higher page-load times during this period, you can determine if this is due to Firefox by checking the data along the Browser dimension.
  • By default, a fixed 1% sampling of your users make up the data pool from which the page timing metrics are derived. See the for details on customizing the Site Speed sample rate.
  • Previous versions of Site Speed required a tracking-code change to add . Sites with the deprecated call still collect speed data at the 10% sampling rate. However, this call will be ignored in the future, and the sample rate will change to the default 1%. Consider updating your tracking code to use to set a higher sampling rate.

How do I enable or disable beacon POSTs being sent back to my server?

Filters that use the beacon automatically inject JavaScript to send the POST
back to the server, and the POST handler is always enabled in mod_pagespeed,
so there’s nothing to do to enable beaconing.

To disable the use of beacons by the image rewriting filters use the directive. If you disable image beacons but enable filters that use
them, the filters will work but not as well as when beacons are enabled.

To disable the POST handler for all filters there are two options: either
disable all the filters that use it, or use a
directive to block it. Filters are disabled using
. An example
directive to block all beacon POST handling that
can be added to your file is:

  <Location /mod_pagespeed_beacon>
    Order allow,deny
  </Location>

If you block POSTs but enable filters that use beacons, depending on the filter
it will either have limited functionality or have no useful effect, but in all
cases pointless processing will occur in both the server and the browser, so
you should disable and forbid these filters if you block POSTs.

Note:Even if you disable all filters that use beacons someone
could use tools like or to send POSTs to
your server. These will have no effect but they will require processing. If you
want to completely disable POST handling use a
directive.

Image dimensions

PageSpeed Modules can shrink an image to its actual display dimensions based
on the design of the page, the visitor’s device, and the visitor’s actions,
to ensure the best user experience without wasting pixels.

You can use the
filter to
shrink the image to the dimensions specified by the and
attributes in the tag or by the
inline attribute.

If you cannot use the
filter,
you can use the

filter to shrink the images to their rendered dimensions. In this case,
PageSpeed injects JavaScript into your HTML that will report the rendered
dimensions to the server, known as «beaconing». After receiving a few beacons,
PageSpeed identifies the dimensions, and shrinks the images.

You can use the

filter to ensure your visitor sees full-resolution images, whether they are
using a retina-based or regular device. Sending full resolution images to all
devices is challenging because different devices may use a different number of
pixels (known as device pixels) for displaying a region of the page
(measured by CSS pixels). For example, a region of 100×100 CSS pixels in a
page is displayed using 100×100 device pixels on an iPhone 3, 200×200 device
pixels on an iPhone 6, and 300×300 device pixels on an iPhone 6+. For the best
visual effect using the least bandwidth, you can resize your image to 100×100
for iPhone 3, to 200×200 for iPhone 6, and to 300×300 for iPhone 6+. Using this
filter, PageSpeed generates images at all of these dimensions, and then
modifies the tags so your visitor’s browser uses the
best size.

Taking the
filter one step further, you can use the

filter to send images of higher resolutions when your visitor zooms in. Using
this filter, PageSpeed injects JavaScript into your HTML that checks the zoom
level of the page and fetches a higher-resolution image if necessary. On the
back end, PageSpeed resizes the image to the proper resolutions.

Image formats

PageSpeed Modules support the most common image formats used on the web.

GIF A legacy but still popular image format. GIF is a lossless format,
so the compressed image is visually identical to the original. It
supports both single frame (still image) and multiple frames (animation).
Despite its popularity, GIF often has poor compression performance,
so PageSpeed converts GIF images to other (better) formats, unless the
images are tiny.
PNG A more recent lossless format designed as a successor to GIF for
single-frame images.
JPEG A lossy format where the compression process removes image detail
that is difficult for the human eye to see. How much data to remove
depends on the quality level. JPEG has two modes, baseline and
progressive. Progressive mode can be used to render the image
incrementally and has a higher compression ratio for large images.
WebP A cutting-edge image format. While it is not yet supported in all
browsers, it is becoming
increasingly
available.
In addition to superior compression performance, it includes features
of all other formats: lossy mode, lossless mode, transparency,
and animation. WebP has added support for these features over time,
so your visitor’s browser may support all, a subset, or none of these
features. PageSpeed automatically detects the features which your
visitor’s browser supports and only uses the supported features in
optimization.

Controlling the use of beacons

The ,
,
and filters, use a to collect information
about the rewritten page so as to optimize the rewriting process. The beacon
is a request sent back by JavaScript inserted into the page
by the filter. The use of this beacon is on by default but it can be disabled
using:

Apache:
ModPagespeedCriticalImagesBeaconEnabled false
Nginx:
pagespeed CriticalImagesBeaconEnabled false;

If you disable image beacons but enable filters that use them, the filters will
work but not as well as when beacons are enabled.

This directive can be used in all scopes including
.

Controlling beacon expiry

Note: New option as of 1.12.34.1

By default beacon data is considered valid for two hours, but if your site has a
lot of pages that change rarely and get few hits you might want to raise this
limit:

Apache:
ModPagespeedFinderPropertiesCacheExpirationTimeMs TtlInMs
Nginx:
pagespeed FinderPropertiesCacheExpirationTimeMs TtlInMs;

Specifying the value for the PageSpeed header

By default, PageSpeed adds an header, in
Apache, in Nginx, with the version of PageSpeed
being used. The format of this header is:

...-

For example:

1.9.32.3-4448

We update these following this schedule:

Major Version
Incremented when we make very large changes.
Minor Version
Incremented for each release since the last major version
Branch Number
Incremented for every release. Always increasing.
Point Number
Incremented each time we build a new release candidate or patch release,
resets on each minor release.
Commit Number
Incremented each time we accept a commit to the PSOL trunk. Always
increasing.

All servers running a given release will have the same value for this header
by default. If you would like to change the value reported, you can use
the directive to specify what to use instead:

Apache:
ModPagespeedXHeaderValue "Powered By mod_pagespeed"
Nginx:
pagespeed XHeaderValue "Powered By ngx_pagespeed";

Note: You cannot suppress the injection of this header. This is because
it is used to prevent infinite loops and unnecessary rewrites when PageSpeed
fetches resources from an origin that also uses PageSpeed.

Не гонитесь за циферками

Да, синтетические тесты могут указать на реальные проблемы сайта. И покопавшись, вы вполне можете найти глючный скрипт, проблемы при загрузке DOM, в общем, лишним разобраться не будет.

Но за цифрами гнаться не стоит, ведь в погоне за ними вы можете натворить реально плохих дел. Поисковые системы при ранжировании учитывают только реальную скорость сайта, собирая статистику браузеров.

На PageSpeed Insight или GTmetrix не ориентируются от слова совсем. Так что если сайт реально долго грузится, событие DOMContenLoaded на нормальной машине происходит не через 1-1,5 секунды, а через 3-4, тогда есть над чем поработать.

На этом с вами прощаюсь, желаю успехов!

Отчет «Время загрузки страниц»

Отчет Время загрузки страниц позволяет выполнять подробный анализ эффективности отдельных разделов. Он содержит следующие вкладки:

  • Статистика: данные о странице в зависимости от различных аспектов.
    • Использование сайта: основные показатели взаимодействия (например, просмотры страниц или показатель отказов).
    • Технические характеристики: показатели сети и сервера.
    • Хронометраж DOM: показатели синтаксического анализа документа.
  • Распределение: доля различных факторов в общем значении.
  • Наложение данных на карту: просмотр различных показателей в зависимости от региона.
    • Использование сайта: основные показатели взаимодействия (например, просмотры страниц или показатель отказов).
    • Технические характеристики: показатели сети и сервера.
    • Хронометраж DOM: показатели синтаксического анализа документа.

Preserving HTML caching headers

By default, PageSpeed serves all HTML with
because the transformations
made to the page may not be cacheable for extended periods of time.

If you want to force PageSpeed to leave the original HTML caching headers
you can add:

Apache:
ModPagespeedModifyCachingHeaders off
Nginx:
pagespeed ModifyCachingHeaders off;

Note: We do not suggest you turn this option off. It breaks PageSpeed’s
caching assumptions and can lead to unoptimized HTML being served from a proxy
caches set up in front of the server. If you do turn it off, we suggest that
you do not set long caching headers to HTML or users may receive stale or
unoptimized content.

Ускорение сайта WordPress на уровне Back-end

Теперь пришло время улучшить работу WP, для этого понадобятся минимальные знания, ибо я предоставлю готовые решения, способные значительно упростить жизнь. Начнем, конечно же, не с самого простого.

Выбор темы

Это ключевой момент. На самом деле движок WordPress довольно-таки шустрый. Его ругают за то, что из «коробки» ничего нет, но я считаю это правильным. Такой подход дает большую вариативность последующей кастомизации. Поставил плагин для SEO какой нужно, добавил функционал, который необходим именно для целевого проекта.

Но не только плагины грузят сайт. Частенько, основным фактором нагрузки становится тема. Стандартные темы WP практически не содержат в себе ничего лишнего, соответственно, не требуют колоссальных ресурсов для генерации страниц. Но ведь функционал данных тем может показаться недостаточным?

И тогда начинается поиск. Рекомендую следующее. По возможности не брать темы с большим количеством скриптов, где все элементы построены на AJAX. Да, они выглядят красиво, но чтобы обеспечить полный функционал, могут быть подключены сотни разнообразных скриптов, которые будут с трудом грузиться. Да и подход к SEO при использовании AJAX несколько сложнее.

Чем чище тема, тем лучше

Обращайте внимание при выборе платных премиальных тем. Часто разработчики стараются удовлетворить максимально широкие потребности конечного потребителя, так что в них будет понапихано всего и побольше

Например, Avada, JupiterX. Там будут конструкторы тем, разнообразные функции для поддержки встроенных слайдеров, некоторые вообще не будут работать без тяжеловесных плагинов.

Лично предпочитаю брать темы из официального репозитория. Простые, без излишеств и слишком широкого функционала. Все, что нужно будет добавить, решу с помощью плагинов или собственного кода.

Плагины

Существует распространенная болезнь среди новичков в WP – плагинобоязнь. Все стараются накодить самостоятельно. Даже когда в этом нет необходимости. С одной стороны правильно, лишних инструментов стоит избегать. Многие популярные плагины включают в себя множество излишеств, становятся очень тяжелыми.

Если нужна только одна функция и плагина под нее нет, то тогда есть смысл создать нужный код самому

На самом деле, не важно, куда внесете код. В виде плагина или в functions.php он будет требовать одинаковое количество ресурсов

Перебарщивать с плагинами тоже не стоит. Чем их больше, тем больше ресурсов потребуется на работу, что может заметно замедлить сайт.

Но использовать можно, если они закрывают ваши потребности. Не бойтесь плагинов, но по возможности урезайте их количество. Чтобы ускорить сайт, уберите лишние. Ищите замены, в которых функционал консолидирован. Тестируйте, пробуйте альтернативы.

Оптимизация JS и CSS

Скрипты, порой, основная часть нагрузки на сайт. Каждый скрипт генерирует запросы, имеет определенный вес, соответственно, притормаживает сайт. Многие рекомендуют объединить скрипты в один файл и построить зависимости для него. Это очень сложный метод, способный впоследствии принести массу проблем.

В отдельно файле придется самостоятельно обновлять код, а после обновлений плагинов и темы все зависимости будут слетать и их придется строить заново. В общем, муторный метод. Поговорим лучше о тех, что более просты в реализации и не требуют огромных затрат времени на поддержку.

Отложенная и асинхронная загрузка JS

Самый простой вариант ускорить сайт WordPress — сделать загрузку скриптов более динамичной. Для этого отличным решением станет отложенная и асинхронная загрузка. Если раньше я обходился простым универсальным кодом, то со временем задача усложнилась и пришлось принять волевое решение и распределить скрипты ручками.

Как правильно все это настроить я рассказал в отдельной статье. Рекомендую ознакомиться, ведь там размести наиболее правильные с точки зрения WordPress методы оптимизации. Кликайте по заголовку.

Перенос скриптов в подвал

Да, убрать скрипты из head и перенести в подвал тоже можно. Достаточно добавить в файл functions.php такой код:

Фактически, все скрипты, расположенные в разделе head будут отключены и подключатся заново в разделе footer. Ничего сложного. Но не всегда это хорошо влияет на сайт

Используйте с осторожностью

Reducing Load by Randomly Dropping Expensive Rewrites

Apache:
ModPagespeedRewriteRandomDropPercentage Percent
Nginx:
pagespeed RewriteRandomDropPercentage Percent;

This is a load-tuning parameter (integer between 0 and 100 inclusive)
that controls the percentage of resource rewrites that are randomly
dropped. Currently only CSS and image rewrites are randomly dropped,
as they are the CPU intensive rewrite tasks. A value of 100 means all
such rewrites are dropped and a value of 0 means no rewrites are
dropped. A value of 75 means that 75% of image and CSS rewrites
(selected at random) are dropped. Do not set this parameter to 100 in
order prevent optimization of images and CSS files, it is more efficient
to instead disable the image and/or CSS filters.

As an example, if the value is 90 then an image fetched only once will
be optimized with 10% probability while an image fetched 50 times
will be optimized with 99.65% probability (1 — 0.9^50). You
may need to tune this parameter to find a value that provides the
right load on your servers and still provides sufficient image and CSS
optimization.

Note: Images within CSS files are not randomly dropped
as this would lead to partially optimized CSS resources.

Using PageSpeed With Virtual Hosts

By default, PageSpeed enables itself for the entire server, with global
options propagating to all
VirtualHosts
(Apache) or blocks (Nginx). Options can be overridden
per host, including the ability the limit which hosts PageSpeed runs on.

Note:
When using Apache, it used to be possible to set
to «off» to stop global configuration from propagating to VHosts. However,
enabling makes PageSpeed options behave like
other Apache options and has been the recommended configuration since 2012. The
option has now been deprecated and will be forced to «on» in the next major
PageSpeed release.

Apache:
ModPagespeed On
ModPagespeedInheritVHostConfig on
ModPagespeedFileCachePath "/var/cache/mod_pagespeed/"
ModPagespeedEnableFilters combine_css,combine_javascript
# Direct Apache to send all HTML output to the mod_pagespeed
# output handler.
AddOutputFilterByType MOD_PAGESPEED_OUTPUT_FILTER text/html

NameVirtualHost *:80
<VirtualHost *:80>
  DocumentRoot /www/example1
  ServerName www.example1.com
  ModPagespeedMapRewriteDomain cdn.example1.com *example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /www/example2
  ServerName www.example2.org
  ModPagespeedMapRewriteDomain cdn.example2.org *example.org
  # Don't want combine_css here
  ModPagespeedDisableFilters combine_css
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /www/example3
  ServerName www.example3.org
  # mod_pagespeed off for this virtual host
  ModPagespeed Off
</VirtualHost>
Nginx:
http {
  pagespeed On;
  pagespeed FileCachePath "/var/cache/ngx_pagespeed/";
  pagespeed EnableFilters combine_css,combine_javascript;

  server {
    listen 80;
    server_name www.example1.com;
    root /www/example1;
    pagespeed MapRewriteDomain cdn.example1.com *example.com;
  }

  server {
    listen 80;
    server_name www.example2.org;
    root /www/example2;
    pagespeed MapRewriteDomain cdn.example2.org *example.org;
    # Don't want combine_css here
    pagespeed DisableFilters combine_css;
  }

  server {
    listen 80;
    server_name www.example3.org;
    root /www/example3;

    # mod_pagespeed off for this virtual host
    pagespeed off;
  }
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *