Loading..
Processing... Please wait...

Product was successfully added to your shopping cart.



[Magento 2] How inlining all css files affects PageSpeed

In today's article I will find out if inlining all css files yields better PageSpeed score.

I will use a default Magento 2.1.4 store. I will take a sample page and will inline all css files right into HTML with the help of a plugin.

Disclaimer: I will be using http/1. I know the results might differ if we are using http2.

 

 

Setup

1. Magento 2.1.4

2. A simple around plugin that matches external css files and replaces them with <style type="text/css"> :

  public function aroundsendContent(
           \Zend\Http\PhpEnvironment\Response $response, 
            callable $proceed){
     $content = $response->getContent();
     preg_match_all('#<link[^>]+(?<=href=")([^"]+\.css)[^>]+>#', $content, $matches);
     $css = '<style type="text/css">';
     foreach($matches[1] as $value)
        $css .= file_get_contents($value);
     $css .='</style>';
     $content = preg_replace('#<link[^>]+(?<=href=")([^"]+\.css)[^>]+>#', '', $content);
     $content = preg_replace('#</head>#',$css.'</head>',$content);
     $response->setContent($content);
     return $proceed();
  }

3. Magento cache and CSS/JS bundle and merge all enabled.

 

Results

The results are quite impressive:

CSS Inline improves PageSpeed by 10 points CSS Inline improves PageSpeed by 10 points
CSS Inline improves PageSpeed (desktop) CSS Inline improves PageSpeed (desktop)

Even if we loose in uncached TTFB ( file_get_contents calls are expensive) we gain more than 10 PageSpeed points for mobile view!

 

What do you think? Should we inline all external css files?

  

Strugle with slow Magento! We can help! Fill out the form below.

 

Like the article? Share:

 

Other articles you might be interested in:

  1. Magento profiler not showing simple fix
  2. How to lower TTFB from 8s down to 0.8s
  3. Magento related interesting content bookmarks #1 - Aug-Sep 2017
  4. 3 steps to make Magento site ready for the holiday season
  5. The fastest way to get 90% PageSpeed score

  

If you find this post interesting do not hesitate to sign up for our newsletter and join the 865 people who receive Magento news, tips and tricks regularly.

Thank You!