Google page speed php

Повышение результатов PageSpeed Insights

1. Переведите сайт на PHP 7, по сравнению с PHP 5 работает гораздо быстрей, сокращается время отклика сервера.

2. Включите gzip в .httacess:

#Сжатие gzip AddOutputFilterByType DEFLATE text/html text/plain text/css application/json AddOutputFilterByType DEFLATE text/javascript application/javascript AddOutputFilterByType DEFLATE text/xml application/xml text/x-component SetOutputFilter DEFLATE 

3. Включите кэширование статических файлов:

#Включение кэширования ExpiresActive On ExpiresDefault "access plus 1 year" ExpiresByType image/x-icon "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType application/x-shockwave-flash "access plus 1 year" ExpiresByType text/css "access plus 1 year" ExpiresByType text/javascript "access plus 1 year" ExpiresByType application/javascript "access plus 1 year" ExpiresByType application/x-javascript "access plus 1 year" ExpiresByType text/html "access plus 1 year" ExpiresByType application/xhtml+xml "access plus 1 year" 

На некоторых хостингах (Timeweb, Beget) данный способ не будет работать т.к. статические файлы отдаются через Nginx.

HTML

Сжатие HTML кода не дает особых результатов, но сделать можно.

function clean_html($html) < // Табуляция и переносы строк $html = str_replace(array("\t", "\r", "\n"), ' ', $html); // Двойные пробелы $html = mb_ereg_replace('[\s]+', ' ', $html); return $html; >ob_start('clean_html');

Из-за удаления пробелов и переносов строк может поехать вёрстка.

CSS

Весь код нужно сжать, есть много сервисов, например CSSO.

Далее возможны три варианта оптимизации CSS стилей:

1. Если стилей не много, без использования отдельного файла вывести их в страницы.

2. Соединить все файлы CSS в один и подключить в .

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

Также нужно исключить инлайновые стили у тегов и включения

внутри .

JS

2. Вынести подключение скриптов из .

3. Сделать задержку инициализации галерей и других плагинов.

Также повышает скорость использование библиотек из CDN Яндекс, Google.

Preload

Добавит пару балов «предзагрузка» ресурсов.

Читайте также:  Java spring orm hibernate

Изображения

1. По возможности перевести изображение в вектор (svg).

2. Сожмите png и jpg программами PNGGauntlet, FileOptimizer или TinyPNG.

3. Гугл предлагает форматы JPEG 2000, JPEG XR и WebP – очень сомнительно, первые два поддерживаются единицами, WebP не откроются в Safari (iOS) и много где еще, но есть методы вывести WebP в браузерах, где они поддерживаются.

Счетчики и виджеты

Яндекс.Метрика, Google Analytics, консультанты отнимают до 20 балов и с ними ни чего не сделать, но можно скрыть их от теста, проверяя $_SERVER[‘HTTP_USER_AGENT’] .

PageSpeed Insights использует следующие user-agent:

Для мобильных:

Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3694.0 Mobile Safari/537.36 Chrome-Lighthouse

Для компьютеров:

Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3694.0 Safari/537.36 Chrome-Lighthouse

Проверка User-agent:

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A versatile PHP Library for Google PageSpeed Insights

License

dsentker/phpinsights

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

An easy-to-use API Wrapper for Googles PageSpeed Insights. The JSON response is mapped to objects for an headache-free usage.

  1. Get an api key from the google developer console for Page Speed Insights.
  2. composer require dsentker/phpinsights
  3. Have fun with this library.
$url = 'http://example.com'; $caller = new \PhpInsights\InsightsCaller('your-google-api-key-here', 'de'); $response = $caller->getResponse($url, \PhpInsights\InsightsCaller::STRATEGY_MOBILE); $result = $response->getMappedResult(); var_dump($result->getSpeedScore()); // 100 var_dump($result->getUsabilityScore()); // 100 

Using Concurrent Requests

Читайте также:  Php как открыть новое окно

$urls = array( 'http://example.com', 'http://example2.com', 'http://example3.com' ); $caller = new \PhpInsights\InsightsCaller('your-google-api-key-here', 'fr'); $responses = $caller->getResponses($urls, \PhpInsights\InsightsCaller::STRATEGY_MOBILE); foreach ($responses as $url => $response) < $result = $response->getMappedResult(); var_dump($result->getSpeedScore()); // 100 var_dump($result->getUsabilityScore()); // 100 >
/** @var \PhpInsights\Result\InsightsResult $result */ foreach($result->getFormattedResults()->getRuleResults() as $rule => $ruleResult) < /* * If the rule impact is zero, it means that the website has passed the test. */ if($ruleResult->getRuleImpact() > 0) < var_dump($rule); // AvoidLandingPageRedirects var_dump($ruleResult->getLocalizedRuleName()); // "Zielseiten-Weiterleitungen vermeiden" /* * The getDetails() method is a wrapper to get the `summary` field as well as `Urlblocks` data. You * can use $ruleResult->getUrlBlocks() and $ruleResult->getSummary() instead. */ foreach($ruleResult->getDetails() as $block) < var_dump($block->toString()); // "Auf Ihrer Seite sind keine Weiterleitungen vorhanden" > > >

Result details by Rule group

/** @var \PhpInsights\Result\InsightsResult $result */ foreach($result->getFormattedResults()->getRuleResultsByGroup(RuleGroup::GROUP_SPEED) as $rule => $ruleResult) < $ruleResult->getSummary()->toString(); >
print $result->screenshot->getImageHtml(); // html image element print $result->screenshot->getData(); // base64 screenshot representation 

$ phpunit —bootstrap «path/to/phpinsights/src/autoload.php»

Submitting bugs and feature requests

Bugs and feature request are tracked on GitHub.

This library depends on JsonMapper by cweiske to map json fields to php objects and Guzzle (surprise!).

PhpInsights is licensed for use under the MIT License (MIT). Please see LICENSE for more information.

About

A versatile PHP Library for Google PageSpeed Insights

Источник

Integrate Google PageSpeed Insights API

Do you know, Google provides a free PageSpeed Insights API to analyze websites? It gives free access to performance monitoring of web pages and returns data with suggestions for how to improve.

Читайте также:  Itext examples in java

Using this API, we can build any system that analyzes the given URLs and displays the grading of the websites. It provides a lot of information (more than you expect 😉 ). So, we need to extract the data that we need from the response.

In this article, we will integrate Google PageSpeed Insights API in PHP and extract some of the data for testing. Without delay, let’s write some code.

First of all, we need get the API URL where we will send the data using GET method. We can to pass different optional parameters according to our need. We will call the below API URL.

https://www.googleapis.com/pagespeedonline/v5/runPagespeed

We need to pass url and other optional parameters. Here, url means the URL of website we need to analyze. The list of accepted parameters are as follows:

  • url is the website url we need to analyze
  • category indicates the information of categories we need. The accepted values are accessibility , best-practices , performance , pwa and seo .
  • strategy is the medium of analysis. Accepted value are desktop and mobile .
  • You can also set other parameters such as locale , utm_campaign and utm_source .

Note: We can pass API key to execute multiple requests at once.

Let’s execute the code using CURL. In the below code, we simply set the new URL with parameters and send request to the API route. The response is stored in $data variable.

The response from the API is pretty large. We need to extract the information we need. For this, we will first convert the json object to array.

Most of our data is stored in audits , categories , and categoryGroups keys. So, we can get the desired values giving the correct key path.

To store all our required information, let’s create an array named $response . Below is a complete sample of how to access and store API response information.

Источник

Оцените статью