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.




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);
     return $proceed();

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



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 Performance Optimization - 7 steps to faster website
  2. Does site speed really matter to SEO?
  3. Magento 2 on PHP7 - 25% increase in performance
  4. 3 steps to make Magento site ready for the holiday season
  5. Free Magento PWA extension review


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

Thank You!