As a website owner, you know that it has to be fast. And you have already read various articles on how to speed up your site, perhaps you have already implemented something. Then it becomes interesting how quickly the site loads. This is where you go to Google PageSpeed Insights as the most popular tool, get an assessment and a list of recommendations from Google. And this is where most of us get lost:
- Is PageSpeed Insights important for SEO?
- Why is my site not rated at the maximum?
- What do all these recommendations mean?
Previously, you turned on caching on your site and expected the PageSpeed score to be nearly perfect, but now you wonder why this plugin didn't fix all the speed issues? Maybe he's not very good? The short answer is that:
Google PageSpeed is irrelevant.
Yes, it does ... but why doesn't it matter?
Page speed vs PageSpeed Insights
Speed (website load time) matters and is an important metric in SEO and also affects user experience. When a Googlebot indexes a site, it does not see the PageSpeed indicator, but only knows the speed itself. Did you know that Google PageSpeed Insights does not measure your site's speed? Yes, read this again:
Google PageSpeed Insights does not measure website speed.
Hello dear readers of the blog site! Today's post will be devoted to the wonderful Google Page Speed tool, which allows you to test any page to explore the possibilities of speeding up its loading ().
It's no secret that search engines, especially Google, have been paying serious attention to this aspect lately, so fast websites get a certain advantage in ranking and higher positions in search results.
Google Page Speed Insights not only detects and indicates all the reasons why the page does not load quickly enough, but also offers specific ways to eliminate them, and some of the problems found can be easily eliminated by the service itself in automatic mode.
What kind of optimization tools does Google offer to speed up websites?
In principle, for each of my projects, I devote a lot of time to page optimization activities that contribute to their fast loading. The only thing that really didn’t get to them was the blog site, which is essentially a visual aid for novice webmasters who are not devoid of healthy ambitions and charged to achieve their goals.
But, since I am a perfectionist by nature, I could not admit that an information web resource, carrying, so to speak, knowledge to the masses, would be in some aspect among the laggards. Therefore, it was decided to make every effort to optimize it, including the recommendations of Paige Speed.
Therefore, I immediately pass on to the description of this tool so that you can evaluate its functionality and apply it in practice for the benefit of your web resources.
Previously, Page Speed Insights could be used as browser extensions and download links were present on a dedicated Google page. Moreover, in order to use it in Mazil, it was first necessary, where Paige Speed was present as its addition:
Now it is no longer possible to use extensions for browsers from Google, although the same plugins, but in a slightly different interpretation, are available on the official web pages of Chrome and Mazila (s). In addition, there is a fully functional eponymous online service Google with exactly the same functionality and no less capabilities. If you go to the Developers section, you will see a link to the Page Speed tool there:
By the way, on the same page PageSpeed Tools All Google site acceleration suggestions are located It seems that the developers of the "empire of good" have taken seriously the optimization and acceleration of the entire Internet space, since in the Developers you will find a link to the Optimization Library ( Integrate the PageSpeed Optimization Library) open source.
Availability of open source software of this project, based on the module " mod_pagespeed", Which is installed on Apache servers (of which, by the way, the overwhelming majority), means that anyone can improve or update it.
That is, in this way it is quite possible, at the expense of the Internet community, to create an acceleration tool close to perfect. How all this will look in practice, time will tell. Naturally, in order to make a full-fledged contribution and achieve success in this good cause, you need to be a sufficiently qualified programmer.
If you take a look at the top screenshot (the information is surrounded by a green frame), you will see there a link to install the latest version of the ready-made module. It may well be interesting for owners who can install it on their servers, providing automatic acceleration of the sites located there.
Moreover, there are two modifications of the Page Speed module: directly for Apache servers and for the Apache + Nginx bundle, where the second plays the role of a proxy server:
By the way, the option of sharing Apache and Ngnix in modern conditions is most in demand and is used by most advanced hosters (including, for example, Sprinthost), since it provides efficient use of resources. So, if you are interested in this method of automatically speeding up sites, you can put your hand to it yourself or strain your hoster.
Google "s PageSpeed recommends (ways to increase the speed of loading site pages)
Above, we considered the possibility, so to speak, of a global increase in the speed of loading websites, which requires specific knowledge (it is likely that this information will be useful to someone, at least in the future).
But for the main part of readers, that is, simple webmasters, the option that is understandable and accessible "here and now" is more relevant. The PageSpeed Insights service fully complies with such conditions, which we will talk about in more detail. For analysis specific page site, enter its URL () on this page:
After the analysis, you will see the Google rating, and both in relation to mobile devices and PC, which is especially valuable. In this example, for the home page of this blog, 76 out of 100 credit for mobile is an average score that can be significantly improved by following the guidelines below.
Moreover, to optimize each resource that slows down page loading, links are given to the relevant sections (in order to get them, click the link "How to fix?"), where you will find descriptions of the necessary corrective actions.
But there is an important point to make here. Necessary analyze pages different types to achieve faster loading times for the entire site. For example, for a standard WordPress blog, the level of optimization in this aspect for the main, categories, static pages and posts can be completely different.
Above, I gave an example of a home page that displays post announcements, but in one of the articles, Paige Speed gave a much lower rating:
This happened because posts are usually much more voluminous and include many different kinds of resources and content (images, videos, scripts). Therefore, it is better to start checking for optimization with them. By the way, from this point of view, start from the assessment that Page Speed provides mobile phones as achieving a decent download speed on such devices requires a lot more body movements.
But even different pages of records may differ in quality. This is also due to the fact that some of them run additional scripts that slow down the loading. For example, the level of optimization of one of these web pages caused me not only surprise, but a real shock:
It is quite obvious that 62 points out of 100 possible is not the result to which one should strive. And all because on this and a number of pages of posts I have a script of the SyntaxHighlighter plugin that initiates beautiful design backlit codes.
There may be several such extensions on the site. In each specific case, you need to decide for yourself how important the plugin is for your resource in terms of the functionality that it provides. And depending on this, you either need to remove it, or take steps to optimize that will help speed up page loading.
The above is especially true for the world's most popular CMS, which is used by the overwhelming majority of webmasters. This multifunctional engine is good for everyone, but it needs to be constantly debugged in terms of reducing the load on the server and reducing the page load time. Therefore, the owners of web resources working on WP should take note of this. And the presence of such a service as Page Speed is very useful here.
Be sure to read all these articles at least in view mode by clicking on the links provided above, perhaps you will find a lot of useful things for yourself. In the future, I plan to return more than once to the problem of speeding up web resources, and therefore you can subscribe so as not to miss the release of fresh publications on this topic.
Finally, watch a helpful video to learn why Page Speed tips are advisory and why you shouldn't follow them fanatically.
Google PageSpeed module for a website: what it can do and how to use it
We decided to experiment and add an accelerator from Google to three projects. What came of it - we find out.
Websites should load instantly. Oh no, sites don't owe anything to anyone? Get on the trolley bus and sit next to the student who is sitting with an iPhone. See if he's ready to wait for some online store to load. Let's just say: three seconds - and the tab is closed. The next result from the search results is used.
By the way, about search results... Website loading speed affects search engine rankings. Proofs and. Sites that “slow down” are less frequently visited by robots, which means they are less likely to be indexed. The place in the search results and the convenience of finding the necessary information suffer from this.
Constantly think about whether your page will load slower on a smartphone than on a PC. And if so, then we will most likely downgrade it in the SERP.
- Matt Cutts, Google
Google has worked hard and released its own speed test tool - PageSpeed. It is easy to find elements slowing down the loading - go here and in the only field we indicate the address that you want to test. A detailed performance report will be ready in a minute. The result will be shown in parrots. Ideally, there are a hundred of them, but try and get it! Even Google itself can't do it: check its services :)
Tests are carried out for both desktop and mobile versions of the site. It is better to navigate by the color scale: the yellow zone will indicate that there are elements that are worth optimizing, the green one will tell you that everything is ok. If the site is in the red zone, speed up and optimize. Otherwise, there is an abyss ahead: while the page is loading, the user will already go to another site :)
There are two ways to optimize your site.
Manual optimization
1. Compress pictures with Photoshop or run them through Optimizilla, For example
The less the pictures weigh, the more jackals, the faster the site loads. We do compression, hide multi-megapixel photos under the cat. Enough 640 × 480 previews. The smaller the picture, the faster the site.
Even on start page Google Developers graphics can be compressed up to 71%.
2. We connect fonts from the site itself, and do not pull them from googlephones
Minus - until the browser has loaded the font, the user will see the annoying Arial or Tahoma.
3. Using the browser cache to the maximum
When the site has already been partially saved by the client, loading will go much faster.
4. Minify JavaScript and CSS
Scripts are not edited every day after release - there is no point in compressing them on the fly. Stop optimizing once after code changes. JS templates are better handled on the server, embed the results in HTML, and use the templates on the client after upload.
5. Shrinking HTML
In practice - removing extra spaces, tabs, line breaks.
6. Remove unused code
You can use the built-in "Chrome" audit. Press F12 and go to the Audits tab. There is a single Run button at the bottom. Does basically the same thing as PageSpeed. Only in real time.
Automatic optimization
Any site consists of dynamic and static elements. Dynamic elements are the HTML code itself, derived from php work and database queries. The rest is static. These are images, JavaScript and CSS.
Automatically optimizing a site can be done with a cool thing from Google - PageSpeed Insights. This module is installed on the nginx server and, after settings, compresses in real time dofiga info, including graphic.
PageSpeed Insights can analyze HTML and optimize resources. Pinch, in short. In the source code, the resources will be located in a different path, not according to what the developer asked to compress the photo. This is worth considering. But the display of the resources will not change. Weight will decrease. This means that the page loading speed will increase and the visitors will become more satisfied :)
However, PageSpeed Insights has limitations. It can only be installed on nginx running on or virtual server... No, a shared server rented somewhere in Germany will not work.
The second limitation has to do with the eternal browser war. Pictures compressed by PageSpeed are converted to the .webp format, which only "Chrome" understands (in the popularly beloved Internet Explorer 6 such a thing will not work). IN latest versions Opera also learned how to display such pictures. Because the engine has changed.
Examples of using PageSpeed Insights
We have installed the PageSpeed Insights module on three projects - on our new site and on two client projects. The module sees which browser the request comes from, looks to see if it is trained to display the webp format and gives either an optimized image or a regular jpeg.
Setting up Sibiriks took about half a day. Something had to be done empirically: they changed it, watched what was happening. Sometimes the zone was green, and it could be completely unpredictable to fly into yellow.
Both versions are now in the green zone. This means that there will be no problems with speed. If the connection speed is good, not some EDGE :)
Within the framework of technical support of the online store of the Vitra factory, we decided to experiment and install the PageSpeed Insights module on it:
Google PageSpeed is a tool that allows you to check the speed of a website. It allows you to estimate the download speed for stationary PCs and mobile devices and provides recommendations that can be used for optimization.
The result of analyzing the site load speed looks like this:
Check site speed with Google PageSpeed Insights and service recommendations
After analyzing the site load speed, you can often get the following recommendations:
Optimize images
The most common service recommendation is related to the best choice images for the site. The graphical content is very heavy and can greatly slow down the loading of resource pages. The most general guidelines are to choose the right format (most often it makes sense to use PNG), image size and quality. So too large an image used as a background can significantly slow down the site's loading speed. You should always check images and reduce their size and quality as much as possible (it makes sense to set the size and quality of images to the minimum acceptable for a particular resource).
Enable Compression
Compression by the web server is an important performance parameter. Enabled by the mod_deflate module in Apache or by the directive in Nginx.
Leverage browser caching
Determines whether the header is passed and data is cached in the user's browser. Caching can significantly reduce the number of requests to the server, which reduces the load on it and increases the speed of sending static data (which is the majority on any site) to the client
Eliminate render-blocking JavaScript and CSS in above-the-fold content
JavaScript code by default is executed as the page is loaded, similarly processed by CSS. Those. If a JS script is included in the body of a document, its rendering is interrupted each time until the script is executed. This can be avoided by adding JavaScript and HTML when connecting the body of the page will be rendered regardless of the executable code.
For example, JS in asynchronous mode can be connected like this:
Minify CSS
Минификация CSS предполагает удаление лишних пробелом и переносов строк, что позволяет сократить время обработки браузером и увеличить скорость загрузки страницы для клиента
Minify HTML
Опция аналогичная предыдущей, но имеет отношение к HTML коду. Для минификации HTML и CSS могут использоваться OpenSource программные продукты, ссылки на которые размещены на сайте сервиса.
Avoid landing page redirects
Определяет используются ли редиректы, любые заданные перадресации с одного домена на другой и с одного сервера на другой означают дополнительные циклы запрос-ответ (запрос к серверу DNS и запрос непосредственно данных), что, естественно, увеличивает время через которое конечный пользователь получит контент сайта. Редиректов по возможности стоит избегать.
Prioritize visible content
В данном случае проверяется размер контента, который должен загружаться при переходе на главную страницу сайта, оптимизация не нужна если объем данных составляет менее 14.6kB сжатой информации, что соответствует размеру congestion window в протоколе TCP и означает, что не требуется повторное установление соединения для передачи информации, которая не может быть передана единовременно.
Reduce server response time
Pagespeed Insights выдает предупреждение о медленном ответе сервера в случае если содержимое страницы отдается менее, чем за 200 мс.
Google PageSpeed является очень полезным инструментом при оптимизации работы сайтов, но не следует доверять ему безоговорочно. Информация, выдаваемая Google PageSpeed не всегда корректна и чтобы понять критерии, которые оцениваются лучше обратиться к документации.
В частности, часто будет отображаться предупреждение, что не используется кэширование, хотя фактически
Скорость загрузки сайта является одним из важнейших показателей юзабильности ресурса, и что немаловажно, это один из сотни факторов ранжирования . Действительно, современный пользователь, который кликнул по ссылке, не ждет загрузку страницы более 5 секунд. Поэтому, чем дольше грузится ваш сайт, тем больше вы теряете потенциальных клиентов.
Более 50% пользователей интернета с мобильных устройств, ожидают практически мгновенной загрузки сайта. Исходя из такой статистики, речь в этой статье пойдет о том, как достичь показателей 100/100 в сервисе Google PageSpeed Insights для стационарных и мобильных устройств на примере сайта "Monitor Backlinks".
Мотивация
Сайт-образец и так загружается довольно быстро, поэтому в данном случае будут улучшаться результаты до возможного максимума.
Однажды, при работе с PageSpeed Tool, было замечено, что сайт компании Google имеет удивительно низкие показатели для мобильных устройств - 59/100. Ситуация с версией для стационарных устройств была лучше - 92/100.
Казалось бы, что они должны были использовать свой же инструмент для оптимизации своего веб-сайта, не так ли? Так неужели результат 100/100 недостижим?
Именно это послужило стимулом для достижения максимально быстрой загрузки сайта, чтобы доказать, что достичь результатов 100/100 реально, и при желании вы также сможете это сделать. Это не одержимость, это просто стремление достичь совершенства.
Стартовые показатели подопытного сайта - 87/100.
В итоге, после применения определенных манипуляций, было получено следующие результаты:
О том, как удалось достичь таких показателей, читайте далее.
Как ускорить загрузку страниц?
Прежде чем приступить к пошаговым действиям согласно инструкции, позвольте отметить, что инструмент PageSpeed является всего лишь ориентиром для веб-мастеров на пути оптимизации ресурса. К тому же инструмент содержит рекомендации по ускорению загрузки страниц вашего сайта, а достижение положительных результатов во многом зависит от настроек сервера.
Обратите внимание, на то, что некоторые из шагов инструкции могут потребовать технических знаний, независимо от используемой системы управления контентом (CMS).
Итак, приступим:
Шаг № 1: Оптимизация изображений
Чтобы изображения загружались быстрее, PageSpeed Insights Tool предложил оптимизировать их за счет уменьшения размеров файлов. Чтобы решить эту задачу, необходимо выполнить две важные вещи:
- Сжать все изображения, используя такие инструменты как Compressor.io и TinyPNG. Это бесплатные инструменты, при помощи которых можно уменьшить размер графического файла более чем на 80%, а в некоторых случаях, без ухудшения качества самого изображения.
- Уменьшить размеры изображений до минимума без понижения их качества. Например, если на сайте нам нужна картинка 150x150px, то и на сервере картинка должна быть соответствующих размеров. Параметры изображений не должны подгоняться при помощи CSS или HTML-тегов.
Согласно вышеупомянутым правилам каждое изображение на сайте было загружено, а также вручную сжато и подогнано по размерам. А чтобы не заморачиваться с оптимизацией изображений после их загрузки на сайт, лучше выработайте привычку изначально оптимизировать все новые изображения, загружаемые на сервер. Каждое новое изображение должно быть сжато и подогнано до необходимых параметров.
PageSpeed Insights предлагает опцию загрузки уже оптимизированных изображений, поэтому их можно загрузить на сервер непосредственно с данного сервиса. То же самое можно сделать и с JavaScript и CSS.
Шаг № 2: Минимизация JavaScript, CSS и HTML
В примере, Google предлагает сократить объемы JavaScript и CSS файлов.
Процесс минимизации позволяет сократить объемы файлов, устраняя ненужные пробелы, переносы, строки, символы и комментарии в JavaScript и CSS файлах. Программисты часто оставляют много места и комментарии во время кодирования, что может удвоить объем JavaScript и CSS файлов.
Чтобы устранить эту проблему, на сервере был установлен Gulpjs. Это инструмент, который автоматически создает новый файл CSS и удаляет все ненужные пробелы. Также он автоматически создает новый файл CSS каждый раз, когда вы вносите новые изменения. В приведенном примере, это помогло уменьшить размер основного файла CSS приблизительно с 300Kb до 150Kb. Такая разница в размерах обусловлена ненужными символами.
Дополнительно уменьшить размеры JavaScript и CSS можно за счет переименования переменных, при условии корректной работы селекторов и обновления HTML.
Оптимизировать JavaScript можно при помощи Closure Compiler, JSMin или YUI Compressor. Вы можете создать специальную программу, которая используя вышеперечисленные инструменты, будет переименовывать файлы и сохранять их в рабочий каталог.
Уменьшить CSS можно, используя инструменты YUI Compressor и cssmin.js.
Минимизировать HTML код можно через PageSpeed Insights. Выполните анализ страницы и выберите "Сократить HTML". Чтобы оптимизировать код кликните на "Просмотреть оптимизированное содержание".
Детальнее об оптимизации JavaScript и CSS файлов вы узнаете по ссылке:
Также можно загрузить оптимизированные файлы непосредственно из PageSpeed Tool.
Вот результаты, полученные после минимизации JavaScript и CSS:
Шаг № 3: Использование кэш браузера
Для многих веб-мастеров этап использования кэширования браузера является самым сложным.
Чтобы решить этот вопрос, пришлось перенести все статические файлы с сайта на CDN (content delivery network/сеть доставки контента).
CDN представляет собой сеть серверов, расположенных в различных местах по всему миру. Они кэшируют статические версии веб-сайтов, такие как изображения, файлы JavaScript и CSS. На серверах CDN хранятся копии содержимого сайта, а при заходе на этот сайт, статическое содержимое загружается с ближайшего сервера.
Например, если основной сервер сайта находится в Техасае, то без CDN, посетителю из Амстердама придется ждать, пока контент сайта преодолеет весь путь от сервера расположенного в США. С CDN, сайт загрузится гораздо быстрее из ближайшего к пользователю сервера, в данном случае из Амстердама. Таким образом, сокращается расстояние доступа к данным и сайт загружаться практически мгновенно.
Вот визуализация того, как работает CDN:
На подопытном сайте все изображения, файлы JavaScript и CSS были перенесены на CDN, а на главном сервере остались храниться только файлы HTML. Размещение изображений на CDN играет важную роль в том, насколько быстро будут загружаться страницы сайта для посетителей.
После вышеупомянутых манипуляций инструмент PageSpeed досадно продолжал предлагать использовать кэширование браузера для отдельных сторонних ресурсов. Вот скриншот:
Чтобы решить этот вопрос, пришлось исправить скрипты социальных сетей путем замены счетчиков, на статические изображения, размещенные на CDN. Вместо сторонних скриптов, которые пытались получать доступ к данным из Twitter, Facebook или Google Plus, для подсчета подписчиков, был установлен автономный счетчик, что и помогло решить данный вопрос.
Но более досадным было то, что вдобавок к проблемам со скриптами социальных сетей работу веб-сайта замедлял код Google Analytics.
Решения проблемы со скриптом Google Analytics довольно сложная задача. Так как Analytics был нужен, и его нельзя удалять с сайта, пришлось искать другие решения.
Google довольно редко меняет код Analytics, раз или два в год. Поэтому, Razvan создал специальный скрипт, который каждые восемь часов проверяет наличие последних обновлений кода Analytics, и при обнаружении обновлений загружает их. Таким образом, можно разместить JavaScript код Analytics на сервер, исключая необходимость загружать его с серверов Google, при каждом посещении.
В случае отсутствия обновлений, код Analytics будет загружаться из кэшированной версии на CDN.
А когда Google обновит код JavaScript, то сервер автоматически загрузит новую версию и обновит его на CDN. Этот скрипт был использован для всех внешних сторонних скриптов.
Вот скриншот из Pingdom Tools на котором показаны все загрузки из CDN, в том числе и код Google Analytics. Единственный файл загрузки с сервера, это файл домашней страницы, объем которого всего лишь 15,5Kb. Устранение всех сторонних скриптов значительно улучшило общую скорость загрузки.
Шаг № 4: Удаление блокирующих кодов
Устранение блокираторов также является довольно сложным этапом в процессе повышения скорости загрузки страниц, требующий хороших технических знаний. Основная проблема, которую пришлось решать - это ревизия всего кода JavaScript начиная сверху от "header" и "body" до расположенного внизу "footer" на всех страницах сайта.
Если ваш сайт на платформе Wordpress, плагин Autopmize, скорее всего, поможет вам решить эту задачу. Проверьте свои настройки, а затем в
снимите отметку с "Force JavaScript" и установите ее на "Inline all CSS".Шаг № 5: Включение сжатия
Шаг № 6: Оптимизация мобильного формата
Анализ мобильного формата показывает адаптивность мобильной версии сайта под различные типы разрешения, использование подходящих шрифтов, и наличие хорошей навигационной системы.
С помощью Google Chrome вы можете посмотреть, как ваш сайт выглядит в различных мобильных версиях. Для этого нажмите на иконку меню (гамбургер) настроек и управления браузером в верхнем правом углу, а затем выберите "Дополнительные инструменты → Инструменты разработчика". На панели инструментов выберите иконку с изображением мобильных устройств. Вот и все, смотрите:
В случае примера, не потребовалось каких-либо радикальных изменений.
Вывод
В результате было выполнено 6 самых важных шагов, которые помогли достичь идеальных показателей 100/100 в Google PageSpeed Tools для сайта "Monitor Backlinks". В итоге была оптимизирована не только главная страница, но и все внутренние страницы.
Среди всех выполненных действий по оптимизации сайта можно выделить три самых важных:
- Использование CDN.
- Устранение блокирующих кодов. (Избегайте JavaScript в теле кодирования, лучше переместите его в низ файлов.)
- Оптимизация размеров и сжатие изображений.
Хочется еще раз напомнить о том, что Google PageSpeed Tools является всего лишь вспомогательным инструментом для оптимизации ресурса. Инструменты предназначены для сокращения времени между запросом (кликом по ссылке) и откликом страницы сайта (отображения первых элементов страницы), чтобы посетители не покидали сайт, так и не дождавшись его загрузки. Также рекомендации, предоставляемые инструментом, необходимо применять с осторожностью, чтобы пользователям не показывалась разваленная верстка или какой-то не стилизованный набор блоков.
Обратите внимание. Быстрая загрузка страниц сайта косвенно влияет на ранжирование ресурса в поисковых системах, то есть: выше скорость загрузки → больше и длительнее посещения → выше ранжирование.
Если вы использовали инструмент Google PageSpeed Insights для оптимизации своего сайта, поделитесь достигнутыми результатами в комментариях.
Также не забывайте о том, что специалисты UAWEB всегда готовы предоставить необходимую помощь в вопросах создания, оптимизации и продвижения вашего веб-ресурса, чтобы каждая секунда проведенная пользователями на вашем сайте приносила вам выгоду!