Lessons
-
Introduction
-
SEO
- Broken links
- Site map
- Semantic markup
- Robots.txt
- References
- Text
- Duplicates
- Basic
- Pictures
-
Speed
-
Minification
-
Minification of CSS to reduce its volume
Minification of the embedded JavaScript code of the page
Minification of the embedded CSS code of the page
Minification of images without loss of quality
Minification of JavaScript files to reduce its volume
Unused CSS code
Data optimization:Image URLs
Animated image format MP4, WEBM, SVG instead of GIF and WEBP
Unused JavaScript code
Using the WebP format in images
Too high-quality images without using compression
Suitable video bitrate
-
Reducing requests
-
An overabundance of small pictures
Grouping CSS files
Grouping JavaScript files
An overabundance of font files
Availability of end-to-end CSS, JS files
The presence of a monochrome font
Uploading duplicate files
Using JavaScript facades
Redirecting JavaScript code
Adding lazy loading
Redirect from/to www version
- Fonts
- Loading time
- Server Settings
- Pictures
-
The first content
-
The sequence of connecting JavaScript files
Font display mode
Setting up a pre-connection
Removing lazy loading
Long JavaScript code execution time
File upload delayed or on demand
The server is located in the same country where the users of the site live
No requests to another country that cause page loading to be blocked
-
Minification
-
Mobility
-
Screen support
-
Adapting the layout to a Full HD computer monitor
Adapting the layout for a horizontal tablet
Adapting the layout for a horizontal phone
Screenshots for the mini-report
How blocks break the page layout
Adapting the layout to an HD computer monitor
Adapting the layout for a vertical tablet
Adapting the layout for a vertical phone
- Comfort
-
Screen support
- Bugs
-
Convenience
- Social networks
- Web Application Manifest
- Favicons
- Basic
- Text readability
-
Vulnerabilities
- Encrypted connection
- Exploits
- Vulnerabilities
Using the WebP format in images
The WebP format has absorbed all the best from JPEG and PNG. It can specify the compression ratio of the image from 0 to 100, like JPEG, and it supports transparency, like PNG. Moreover, the compression algorithm is often more efficient than the JPEG format.
The only disadvantage of this format is that it is not supported by operating systems by default. That is, users will not be able to download to their computer and open a WebP file. To do this, they will need to install additional software. But in the browser it always opens.
When converting JPEG and PNG to WebP, it is recommended to specify a compression quality of 90. This will greatly reduce the file size compared to 100 quality, while the image will be almost identical to the maximum quality. It is better to save GIF images without compression.
Code for integration
It is necessary to consider the following:
- Support WebP 95.86%, and AVIF 94.7%. Check the Accept request header for the image/avif and image/webp strings. So, browsers report that they support these formats.
- Each framework and CMS has standard functions for working with images. As a rule, their functionality can be expanded. Therefore, instead of using your function, it is better to extend the standard functions of the framework and CMS. Methods for extending the standard functionality of each system have their own and are called: hooks, events, function redefinition, callbacks. When using your function, you will need to fix a lot of site files in order to change the call to the image generation function to your own. The easiest way is to modify the standard function 1 time, which is used everywhere.
<?php
/**
* Сначала убедитесь, что ваша версия PHP поддерживает AVIF и WebP. Для этого используйте функцию phpinfo() или выполните:
* php -i | grep AVIF
* AVIF Support => enabled
* php -i | grep WebP
* WebP Support => enabled
*
* В случае отсутствия поддержки форматов AVIF и WebP нужно их настроить. Инструкции для вашей операционной системы можно найти в интернете.
*
* Для ubuntu обновите вашу версию PHP из репозитория ppa:ondrej/php. Для этого выполните:
* add-apt-repository ppa:ondrej/php
* apt update
* apt upgrade php8.3
*
* Вместо 8.3 укажите свою версию PHP.
*/
/**
* Функция конвертирующая изображения в формате PNG, JPEG, GIF в AVIF, WebP
* - Проверяет, поддерживает ли браузер данный формат
* - GIF изображения конвертирует с качеством 100
* @param string $sourcePath — абсолютный или относительный путь до изображения
* @param int $quality — качество
* @return string — путь SRC
*/
function img2avif($sourcePath, $quality = 90) {
// Узнаём поддерживаемые браузером форматы
$accept = $_SERVER['HTTP_ACCEPT'] ?? null;
// Получаем информацию о файле
$info = pathinfo($sourcePath);
// Путь до конвертированного файла
$path = ($info['dirname'] ? $info['dirname'] . DIRECTORY_SEPARATOR : '') . $info['filename'] . '.';
// Путь до корня публичной директории
$root = $_SERVER['DOCUMENT_ROOT'] ?? '';
// Проверяем поддержку форматов и сгенерированные файлы
if(strpos($accept, 'image/webp')) {
$type = 'webp';
$path = $path . $type;
} elseif($accept === null || strpos($accept, 'image/avif')) {
$type = 'avif';
$path = $path . $type;
} else {
return str_replace($root, '', $sourcePath);
}
if(!is_file($path)) {
// Загружаем картинку в переменную PHP
$image = imagecreatefromstring(file_get_contents($sourcePath));
// Для GIF нужно качество 100
if($info['extension'] === 'gif')
$quality = 100;
if($type === 'webp')
imagewebp($image, $path, $quality);
elseif($type === 'avif')
imageavif($image, $path, $quality);
}
return str_replace($root, '', $path);
}
?><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Результат работы PHP функции, конвертирующей JPEG в WebP</h1>
<img src="<?=img2avif('./photo.jpg')?>" />
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Результат работы PHP функции, конвертирующей JPEG в WebP</h1>
<img src="./photo.jpg" />
</body>
</html>