How to increase the speed of site load


15-08-2018
Денис Л.
Оптимизация сайта
How to increase the speed of site load

Increasing the speed of downloading a site is the task of any self-respecting web developer. No matter how beautiful and modern your site is, if it takes a long time to load - it negates all the works on its beauty of design and functionality. And if your site does not load more than 5 seconds - then most users will simply close it and go to another.

There are a lot of ways to optimize the download speed. There are automatic, manual and combined. We will consider the basic principles suitable for any site and any CMS.

Beforehand, it makes sense to download your site in the browser, open the debugger (F12), go to the Network tab, tick "Disable cache", refresh the page, and then record the number of requests, as well as the total download time of the site. Based on the results of the work you can compare the result.

Before starting work, make a full backup of the site and database site. Part of the work requires knowledge and experience. If you are a beginner and are not sure of your abilities - you do everything at your own peril and risk!

So, how to speed up the site load:

First, let's see the main recommendations from Google PageSpeed Insights.

To do this, go to the browser at: developers.google.com/speed/pagespeed/insights/

Enter the address of the site under test, click "Analyze".

Among the list of recommendations, often in the first paragraphs, there is a point about image optimization. How to replace all images automatically, especially if there are a lot of them, is written in my record about automatic image optimization using a script.

Among the recommendations for certain will be a recommendation about activation GZIP on server. To do this, insert the following lines into the .htaccess file:


<ifModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml application/xhtml+xml text/css text/javascript application/javascript application/x-javascript
</ifModule>

If among recommendations there is a recommendation about caching ("Use your browser's cache"), in the file .htaccess we insert the following lines:


<FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf|js|css|pdf)$">
Header set Cache-Control "max-age=864000"
</FilesMatch>

In this example, we force the browser to cache the extension files flv | gif | jpg | jpeg | png | ico | swf | js | css | pdf for 10 days (864000 seconds).

Now we need to merge all styles files into one file. This is necessary for the site to have fewer requests to the server. Each additional request to the server increases the load time of the site. Fewer requests - faster downloads.

There are options automatic (via Nodejs + gulp + plug-ins concatenation and minimization). This topic deserves a separate article (I'll write it later). Now consider a simple version and do everything manually.

  • We are looking for all style files referenced from the <head>
  •     
  • Copy all the styles to a single file. Next, go to the css: autoprefixer.github.io/en/ site. This site will find errors in our styles (if any), and also adapts styles to all browsers (adds the necessary vendor prefixes and removes unnecessary).
  •     
  • Then go to the minimization site css: rudrastyh.com/tools/css-minifier
  •     
  • Put a checkmark to one style was one line.
  •     
  • We copy the resulting styles and save them in our file, after deleting the old styles (!).

If you have a CMS, for example Wordpress, then some styles are called by plugins. And after combining styles, they will still be called in the site code. Thus, in advance you will need to make a decision: if you want to speed up the site and combine styles into one file, then you have to disable auto-update of the Wordpress system and plug-ins, because if you do not, then after updating any plug-in, the styles will again fall into the domain head. If you still decided - then go to the folder with plug-ins /wp-content/plugins/, copy it to yourself on the computer and through a text editor by searching the files, look for the line of calling the styles, namely wp_enqueue_style. Comment out this line (put two oblique slashes // before the beginning of the line). Refresh the page, look at its code. You should see that the styles are less by 1. Do this for all the plugins whose styles are in the head area.

You can go further and make only the styles that are used only on the main page for the main page. There is an excellent service for this site: uncss-online.com. He analyzes your page and gives you only those styles that are used on this page. Note that if you have pop-up feedback forms, interactive menu items, then you need to copy these styles manually. To use the resulting styles, you will need to write in the head region condition: if we are on the main page, then we load only the styles file of the main page, in all other cases we load the common style file. Example of a function for a site on php:

<?if($_SERVER['REQUEST_URI']=='/'):?>
    <link rel="stylesheet" href="style_home.css">
<?else:?>
    <link rel="stylesheet" href="style.css">
<?endif?>

We check whether there are scripts in the head area. If there is, we transfer them to the footer. Scripts block the download of the site and all of them should be located in the basement of the site. The sequence of loading scripts is the same as before. Then we assign an attribute to each script defer, without any parameter. Then the scripts with this attribute will be loaded asynchronously, but exactly in the order in which they are specified in the html.

As a result, all our scripts should be loaded asynchronously and do not delay loading our site.

If you have a CMS, for example Wordpress, then part of the scripts is called by plugins. And, there is a general function that sets the attributes for all CMS scripts and plugins. This is a function print_extra_script, which is in the file /wp-includes/class.wp-scripts.php. Look for the function in the function where the variable is defined $tag. We delete there part of the code type='text/javascript' (the 'type' attribute is no longer needed for any browser) and insert the attribute defer. Without any meaning. After that, all scripts will become asynchronous.

If we have a lot of images on the main page of the site (for example, carousels with partners 'and customers' logos or many pictures with examples of work performed and others), that is an excellent optimization option: we change the algorithm for loading all the pictures of the carousel. We are looking for a template file that displays these pictures. At the image we change the attribute src to attribute data-src. And in the attribute src we enter the path to a pre-prepared image of the same size as ours, but a few bytes in size. To do this, first look at the size of the image that we have on the site: open the browser debugger (F12), direct the mouse to the image in the code and the debugger shows us the used size (we are not interested in the original size, but in the used one, it will be smaller). Next, in Photosop or any other image editor, create a new blank image of the correct size, for example 300x400. Save it for Web, in the most minimal quality. If we save in the format png, then we select the format 8-bit. Total, the image will be less 1 Kb. And for all the pictures of the carousel we put a link to this image. And in our scripts we write the javascript code, which after loading DOM will take the contents of the attribute data-src and replace them src every picture of our carousel. Thus, the initial weight of the site will decrease significantly. For example, on a project where there are many such images, the weight of the site can be reduced by 1 Mb and more.Those. images will initially be downloaded with a white background, and in the process of building a site they will be replaced with real pictures.

Here is the code that will change the data-src attribute to src after the page is loaded:

Option 1 (if you have a jQuery library on your site)


<script>
function changeDataSrcToSrc(i,e) {
    e.src = $(e).data('src');
}

window.addEventListener("load", function() {
    $('[data-src]').each(changeDataSrcToSrc);
});
</script>

Option 2. If you do not use the jQuery library (and do it correctly)


<script>
window.addEventListener("load", function() {
    document.querySelectorAll('[data-src]').forEach(function(i) {
        let src = i.getAttribute('data-src');
        i.setAttribute('src', src);
    })
});
</script>

If the recommendation from Google PageSpeed Insights there is information about the long response time of the server (more 300-500 ms), then you need to contact your hosting provider to investigate this problem. The normal server response time is the time within 150 - 200 ms. Perhaps, your hosting specialists will meet you and adjust the server settings for a faster response. If not, they can offer you a different tariff plan or a dedicated server (which is the fastest solution for any heavily loaded site).

Remove unnecessary pictures from the site. For example, in the header of the site you have a slider. For sure it's a classic slider, the full width of the screen, with large pictures in high quality. Think about how important you are to all the pictures of this slider? Maybe you should just leave one picture there? Or even turn off the slider + delete the script that loads it? And leave one single, optimally optimized picture, the slogans on which will be changed using javascript (I'll tell you in the nearest posts how to do this). You will be surprised how much faster your site will be loaded!

Replace all icons made in the form of graphic files on the icon font. There is an excellent service: fontastic.me. It allows you to make an individual set of fonts for your site, in which you can only include those icons that you really need. There are icons of arrows, social networks, ... and everything, anything. Your personal icon set will weigh no more than 15-20 Kb. In this case, the download of all of them will require only 1 request to the server. In addition, you can manage these icons: set them to any size, shadow, color, while, unlike the pictures, the font will be of perfect quality in any possible size.

Based on the results of the work it is necessary to analyze the result: open the browser debugger (F12), go to the tab Network, update the page and look at how much the number of requests and download time has decreased.

In this post, I gave only some, the most basic principles of optimization. Applying them all, your site will load in a split second. There are many other methods for optimizing content, but I'll talk about this somehow in other posts...