On the site backend works for 50 ms, and the front takes a lot of time. As a result, half a second to display the page using the cache, without a cache of 700 ms. There are rules and ways to increase the display speed?

For Beka used Laravel.

  • Why optimize something that does not need it? Well, you get the benefit of 100-150 milliseconds, the user is unlikely to notice. Does it make sense to do according to the Pareto rule? - Daniel Protopopov
  • one
    @DanielProtopopov If you start now, it will be difficult to get rid of it later - Shadow33
  • 700 ms is the rendering time or response time? - Ilia w495 Nikitin
  • 700 is the server response time + render time - Shadow33

6 answers 6

Optimization js is one of the hot topics. What can you do:

1) You can use the built-in chrome profiler http://prntscr.com/ejumdm and analyze which script / method you have most loaded and optimized.

1.1) There is for example the Google PageSpead mechanism

2) Minimize scripts. For good, you can minimize scripts and styles with the tools to build grunt , gulp .

3) Even minimization does not help. You can use AMD for asynchronous loading of modules. For this you can use, for example, webpack

  • I would sitepeed.io along with or instead of Google PageSpeed ​​mentioned. Thank. - Sasha Chernykh
  • one
    @ SashaBlack yes, for sure. I forgot to mention it by the way. Very cool stuff. - Kostiantyn Okhotnyk
  • one
    sitespeed.io is a performance toolkit. And some of them webpagetest very handy thing. Here, for example, on this screen it is already possible to conclude that the pictures require compression. And that styles are also loaded for a long time (as it turned out there is a picture in base64). - Kostiantyn Okhotnyk

I would advise you to optimize all static content on the site.

Compression graphics

In your case, in addition to compressing styles and scripts, I advise you to compress and graphics. For example, pictures can be easily compressed without losing quality only by deleting exif-data. On a real site, you can reduce the size of images by an average of 70%, which on a modern site is approximately 4 MB. Example on gulp :

 var gulp = require('gulp'), imagemin = require('gulp-imagemin'), imageminJR = require('imagemin-jpeg-recompress'), imageminSvgo = require('imagemin-svgo'); // Optimizing images gulp.task('imagemin', function() { gulp.src('./img/**/*') .pipe(imagemin([ imageminJR({ method: 'ms-ssim' }), imageminSvgo({ plugins: [ {removeViewBox: false} ] }) ])) .pipe(gulp.dest('./public/img/')) }); 

And for browsers that understand the lightweight webp format (format developed by Google), you can also make this version of the images:

 var gulp = require('gulp'), webp = require('gulp-webp'); // Generate Webp gulp.task('webp', function() { gulp.src('./img/**/*') .pipe(webp()) .pipe(gulp.dest('./public/img/')) }); 

Script optimization

First merge all the scripts into one file and minify them. This litter reduces the number of HTTP requests and file size:

 var gulp = require('gulp'), concat = require('gulp-concat'), uglify = require('gulp-uglify'); // Concat JS gulp.task('js', function(){ gulp.src([ './js/jquery.js', './js/wow.js', './js/menu.js', './js/scrollspy.js', './js/main.js', './js/temp/contact.bundled.js', './js/owl.carousel.js' ]) .pipe(concat('script.js')) .pipe(uglify()) .pipe(gulp.dest('./public/js/')) }); 

Style optimization

In addition to the usual minification of styles, you can also use advanced - to combine duplicate classes and @media. An example of a gulp from my [web-starter-kit] [1]:

 var gulp = require('gulp'), stylus = require('gulp-stylus'), // Минифицирует CSS, объединяет классы. Не ломает CSS, в отличие от cssnano, который, к примеру, может неправильно выставлять z-index csso = require('gulp-csso'), // Объединяет все @media cmq = require('gulp-combine-mq'), // Сокращает CSS-селекторы gs = require('gulp-selectors'), // Проставляет вендорные префиксы autoprefixer = require('gulp-autoprefixer'), livereload = require('gulp-livereload'), nib = require('nib'); // Compiling Stylus in CSS gulp.task('css', function() { gulp.src('./styl/*.styl') .pipe(stylus({ use: nib() })) .pipe(cmq()) .pipe(csso()) .pipe(autoprefixer('last 3 versions')) .pipe(gulp.dest('./public/css/')) }); 

And if you really have nothing to do, then you can also reduce the selectors

 // Minify selectors gulp.task('gs', function() { var ignores = { classes: ['active', 'menu', 'nav', 'slide', 'error', 'form-control', 'loader', 'showLoader', 'fadeLoader', 'webp', 'wow', 'owl-*', 'i-*'], ids: '*' }; gulp.src(['./public/**/*.css', './public/**/*.html']) .pipe(gs.run({}, ignores)) .pipe(gulp.dest('./public/')) }); 

By the way, for sure you have classes that are added through JS, so you should first put all such classes in the ignores variable.

Caching static on the user side

I would also advise caching scripts and styles on the user's side to prevent them from being re-loaded if they have not changed:

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

And enable gzip compression on the server:

 # сжатие text, html, javascript, css, xml: <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> 

    You need to look at the details of your case in DevTools / Timeline and use each of the methods with an eye to it, because general optimization tips can only do harm in a particular case. I can add the following to the tips above:

    • See the timeline details of your critical rendering path . Try to minimize it:

      1. Remove the blocking CSS from it. Select, for example, using critical styles for the first screen and put them inline in <head><style> . The rest of the CSS is loaded asynchronously using loadCSS .
      2. Download scripts with the defer / async attribute.
    • Actively use <link rel="preload"> - in modern browsers the increase in speed is very significant, but it must be used with the mind and timeline.

    • Images to cook in several sizes and use the tag <picture> ; give images in WebP format to browsers that can read it using the same tag.

      1. Do not inline images passed through a base64 decoder (in CSS too).
      2. If there are a lot of images, it is “lazy” to load them, for example, with the help of lazysizes (it is good to be friends with <picture> ).
      3. If there are heavy PNGs that use transparency, look in the direction of converting such PNG to JPG + SVG.
    • If you use custom fonts, I also recommend that you download them asynchronously, for example, using fontfaceobserver .

    Sources:

    An article about optimization in general: https://dev.to/sanjsanj/optimising-the-front-end-for-thebrowser

    About <link rel="preload"> https://medium.com/reloading/a-link-rel-preload-analysis-from-the-chrome-data-saver-team-5edf54b08715

    WebP https://css-tricks.com/using-webp-images/

    Base64 https://csswizardry.com/2017/02/base64-encoding-and-performance/ , https://csswizardry.com/2017/02/base64-encoding-and-performance-part-2/

    PNG → JPG + SVG (Transparent JPG) https://css-tricks.com/transparent-jpg-svg/

      First, run a few key pages through Google PageSpeed ​​Insights. Google will give you about such problems and recommendations:

      1. Configure caching of static resources (css, js, images). This can be done with the help of nginx settings. And if you have shared hosting - contact technical support. Usually they do it for free.
      2. Squeeze all the images on the site. Https://optipic.io/ru/ helps to automate this process - it just connects to any site on php without any "tambourine dances". Download the script to your site, and the service itself will find all the pictures and compress them.
      3. Combine all css in one css-file, all js in one js-file.
      4. Transfer as much as possible all css and js to the bottom of the html-code.
      5. Get rid of all the resources that give 404 error (or correct the links to them).

      Plus, run the key pages through https://tools.pingdom.com/ . This service will give you an understanding of exactly which resources slow down page loading. For example, it often turns out that some third-party widgets slow down a site or large (heavy) resources (video, big js, etc.). With third-party widgets, you can try using async or chat with their technical support (they should be interested in their widgets loading as quickly as possible). If neither that, nor that does not help, then look at alternative third-party services that load more quickly.

        It is necessary to compress images, scripts, all resources, combine and cache.

        .htaccess for the lazy (gzip, caching):

         <IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews </IfModule> RewriteEngine On #GZIP AddEncoding gzip .gz RewriteCond %{HTTP:Accept-encoding} gzip RewriteCond %{REQUEST_FILENAME}.gz -f RewriteRule ^(.*)$ $1.gz [QSA,L] RewriteCond %{HTTPS} off RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/$ /$1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] #GZIP AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript </IfModule> ServerSignature Off <ifModule mod_headers.c> #кэшировать html и htm файлы на один день <FilesMatch "\.(html|htm)$"> Header set Cache-Control "max-age=43200" </FilesMatch> #кэшировать css, javascript и текстовые файлы на одну неделю <FilesMatch "\.(js|css|txt)$"> Header set Cache-Control "max-age=604800" </FilesMatch> #кэшировать флэш и изображения на месяц <FilesMatch "\.(flv|swf|ico|gif|jpg|jpeg|png)$"> Header set Cache-Control "max-age=2592000" </FilesMatch> #отключить кэширование <FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$"> Header set Cache-Control "no-store, no-cache, max-age=0" </FilesMatch> </IfModule> <ifModule mod_expires.c> ExpiresActive On #по умолчанию кеш в 5 секунд ExpiresDefault "access plus 5 seconds" #кэшировать флэш и изображения на месяц ExpiresByType image/x-icon "access plus 2592000 seconds" ExpiresByType image/jpeg "access plus 2592000 seconds" ExpiresByType image/png "access plus 2592000 seconds" ExpiresByType image/gif "access plus 2592000 seconds" ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds" #кэшировать css, javascript и текстовые файлы на одну неделю ExpiresByType text/css "access plus 604800 seconds" ExpiresByType text/javascript "access plus 604800 seconds" ExpiresByType application/javascript "access plus 604800 seconds" ExpiresByType application/x-javascript "access plus 604800 seconds" #кэшировать html и htm файлы на один день ExpiresByType text/html "access plus 43200 seconds" #кэшировать xml файлы на десять минут #ExpiresByType application/xhtml+xml "access plus 600 seconds" </ifModule> 
        • thanks, my gzip is configured via nginx - Shadow33

        Why did no one go deeper?) Make Apache a backend and Nginx reverse proxy for the frontend, thereby having high speed!