Google PageSpeed Insights: automatic optimization of site images


23-07-2018
Денис Л.
Оптимизация сайта
Google PageSpeed Insights: automatic optimization of site images

Website optimization is not an easy task. It is necessary to take into account a huge number of factors.

For an especially long time, you can transfer images, for example, in systems such as Wordpress or Bitrix, because there each image is in a separate folder. And if such folders are more than 100, and in online stores and more than 1000, the process of copying images can take several days of routine work ...

I, as a web developer, regularly optimize sites, and one day I came up with the idea to write a script that does this all in automatic mode.

Since the Google PageSpeed service analyzes only one particular page at a time, this script optimizes only those images that are included in this analysis (ie images on one particular page). If your site is on a dedicated server, you have a good command of the console and at least are familiar with Node.js, then you will be more interested in my post "Node.js: how to recursively compress all images on the site".

If in addition to optimizing images you want to significantly increase the speed of loading your site, then I write more about it in a post: "Speed ​​of site loading and how to increase it ".

Script for optimizing images from developers.google.com/speed/pagespeed/insights/


Bitbucket link: https://bitbucket.org/lisogorsky/dev/src/master/copyImgFromGoogle/


Initial steps:

  1. We go to the site through the ftp client
  2. Create a folder in the root of the site named _image_min
  3. Create a file with the extension .php (for example imgMinCopy.php), into which we copy the code that goes just below

To get started, you need to give the script file the rights 0755. Then do 0644 again.

We analyze the site through the service https://developers.google.com/speed/pagespeed/insights/

Find a box named "Optimize images"

Looking for this block phrase: "Optimize the following images to reduce their size by ..."

Click on this line with the right mouse button, select "View code".

A code editor is built into the browser.

Looking for <div class="url-block">

Click twice on the "url-block", press the right arrow on the keyboard (not to overwrite the name "url-block" and add the class "my").

You should get: <div class="url-block my">

go to the Console tab, enter the code below:

let urls=document.querySelectorAll('.url-block.my [data-title]');let arr = []; let result = [];
for(let i=0;iarr.push(urls[i].dataset.title);}
for(let i in arr){let ddd=(arr[i].split('/')).slice(3);result.push(ddd.join('/'));}
console.log(result);  // ---> in the end, we get an array of desired image references

Download from the Google PageSpeed Insights folder with optimized content. We extract the contents of the image folder.

In the folder named "_image_min" (which we created earlier) we place optimized images received from Google.


Below is the code of the file imgMinCopy.php

<?php header('Content-Type: text/html; charset=utf-8');

$imgMinFolder = '_image_min/';

$backupFolder = 'backup/'.date("H-i-s_d-m-Y"); $imgArr=[]; $i=0;

$imgPath = []; // Here we enter an array of references to those images that need to be optimized (we take the array from pagespeed)

foreach(glob($imgMinFolder.'*.*') as $filename) {
	$name = strstr($filename, '/');
	foreach($imgPath as $path) {
		if(strpos(mb_strtolower($path), $name)) {$arr = [substr($name,1), $path];}
	}
	array_push($imgArr, $arr);
}

mkdir($imgMinFolder.$backupFolder, 0755, true);
foreach($imgPath as $img) {
	$nameBackup = strrchr($img,'/');
	if(copy($img, $imgMinFolder.$backupFolder.$nameBackup)) {$backupResult = true;}
}

// echo "<pre>";
// print_r($imgArr);

echo "<table style='border-collapse:collapse;border-spacing:2px;'><style>td{border:1px solid;padding:2px 10px}</style>";
foreach($imgArr as $keys) {
	$file = $imgMinFolder.$keys[0];
	$newPath = $keys[1]; $i++;
	if(copy($file, $newPath)) {
		echo "<tr><td style='text-align:right'>{$i}</td><td>File {$file}</td><td><b style='color:#0bef0b'>успешно</b></td><td>copied along the way: /{$newPath}</td></tr>"; unlink($file);
	}else{
		echo "<tr><td style='text-align:right'>{$i}</td><td>File {$file}</td><td><b style='color:red'>failed to copy</b></td><td>along the way /{$newPath}</td></tr>";
	}
}
echo "</table>";

if($backupResult) echo "<h3>A backup copy of the replaced images was created at: {$imgMinFolder}{$backupFolder}</h3>";

?>

Next we go to the address of your site and after the '/' we specify the name of the script, for example: http://site.ru/imgMinCopy.php

The script will display information about the successful copying of images, and also specify the folder in which the backup copy of the old images was created. After you make sure that everything is correct, you can delete the backup folder.


Video instruction