Magento Optimization for Google PageSpeed Insights – the Complete Guide on Getting to the 100 Score

Magento Optimization for Google PageSpeed Insights – the Complete Guide on Getting to the 100 Score

Magento Optimization for Google PageSpeed Insights – the Complete Guide on Getting to the 100

It’s a Hard-Knock Life

Even a fast Magento store can have an average PageSpeed Insights score. You should understand though that these metrics are not 100% accurate. After all, Google doesn’t see your site the same way as your customers do. It doesn’t take into account the subtleties of e-commerce user experience and many Magento quirks we have to deal with every day.

Nevertheless, Google PageSpeed Insights tries its best to analyze the store and generate actionable recommendations for any page. Our task as Magento developers is to correctly understand what it tries to communicate and create effective solutions to fix everything wrong with the store.

To get the best score you are guaranteed to invest quite a bit of your time into analyzing, fixing, and debugging every Google Pagespeed opportunity and our guide is here to help.

Our Google PageSpeed Insights services audit will focus on mobile-first experience. To explain our mindset, we want to hammer home 3 points:

  • First, because mobile purchases are on the rise.
  • Second, because Google values mobile user experience higher than desktop.
  • And third, because it’s harder to optimize for slower mobile networks and smaller devices. But when you do that, your desktop score will also rise.

Take a look at the discrepancy of desktop versus mobile score of this Magento store.

desktop rating magento pagespeed insights

mobile rating PageSpeed Insights Magento

The gap is huge. This is what we are talking about. Your desktop score might be fine. Your mobile score probably sucks, though, and few PageSpeed Insights services stress that enough.

PageSpeed Insights Magento desktop vs mobile metrics

How Google PageSpeed Insights Ranks Sites

Only 2% of all websites have 100% PageScore score. This is the ideal score. Most of the time, 100 is an attainable but not entirely justifiable goal.

We often have to explain to our customers why they want to balance store performance, development costs, and customer satisfaction instead of going for the best score no matter what.

As with all things in life, there’s an unspoken industry standard in store performance. The higher you go after that, the more costly it becomes. In order to avoid overpaying for further marginal improvements (the law of diminishing returns) instead, we suggest you need to find the point where the performance score offers the best return on investment – the point where your store runs at optimal performance.

Getting the Best Lab Data Metrics

The metrics results are not weighted equally. Currently the weights are:

  • 5x – Time to Interactive
  • 4x – Speed Index
  • 3x – First Contentful Paint
  • 2x – First CPU Idle
  • 1x – First Meaningful Paint
  • 0x – Max Potential Input Delay

As you can see, one parameter has 0 weight. It doesn’t mean it’s not important, just complicated enough that Google decided to exclude it from the equation (for now).

There are of course more than 6 metrics that affect the final score. Although Google Pagespeed essentially uses Google Lighthouse to audit the site, not all audits are included in the score. Just keep in mind that they are more numerous than they show you. If you need more info – we have a guide for Magento Lighthouse optimization.

Time To Interactive

Google has given TTI the highest possible weight among any other metrics, x5. That’s why improving TTI will be our top priority job. Most impactful changes you need to do to improve TTI for Magento stores:

  1. defer or remove unnecessary JavaScript code,
  2. clean up you codebase and kill dead code that slows you down,
  3. split JS code into two parts, move less important JS to the bottom of the page.

Speed Index

With 4x weight, Speed Index is the second most important Lab Data parameter. Quick guide on how to improve it for Magento:

  • optimize content efficiency: minimize code and media size, employ code compression, optimize images and switch to newer and faster image standards, configure smart JS bundling, manually profile the page for other issues.
  • optimize Critical Rendering Path: reduce CSS styles, the number of DOM elements, rewrite HTML where possible to make it lighter, take non-important clutter off the Critical Rendering Path by splitting up CSS files, speeding up HTML parsing and DOM tree creation, improving render tree construction,
    etc.

First Contentful Paint

An efficient First Contentful Paint stands on 5 pillars that improve Magento FCP metrics:

  1. minimal amount of render-blocking CSS and JS,
  2. setting up an efficient cache policy to serve static assets,
  3. compressing and minifying text, CSS, and JS files,
  4. optimizing leftover JS files to run faster,
  5. getting rid of unused JS code instead of continuously piling it together.

First CPU Idle

CPU performance is the most common bottleneck for Magento stores. That’s why before you look at anything else, look at your CPU first. First CPU Idle depends heavily on how well your content efficiency delivery works. Second largest aspect is Critical Render Path. This is what makes for a lightweight, fast-moving Magento store.

First Meaningful Paint

FMP interweaves closely with other lab data that leans on Critical Render Path speed. All recommendations we give above apply here. FMP has a low weight of 1x compared to other Lab Data metrics but its interconnected nature with for example First Contentful Paint or Speed Index means you can’t improve one without affecting the other.

Max Potential Input Delay

This no-score piece of Lab Data metrics might seem like a non-issue but you should at least take a look at how you perform here. Poorly thought-through iframes, server-side rendered JS apps, and other factors can give you a general overview of how things are in non-mission critical parts of the store. Even though for now Max Potential Input Delay doesn’t get included in the final score, who can guarantee it will always stay that way?

Why Opportunities Matter

Opportunities is a series of Google Pagespeed audits that help structure your website issues and fix them one by one. Each audit will improve one or more Lab Data metrics. Some audits are not really that important and get included as a recommendation. Others are true roadblocks and they offer significant boosts to your Magento performance.

No matter the importance, we’ll go through the entire list so you know how to deal with any of these issues.

Eliminate Render-Blocking Resources

kill_render_blocking pagespeed insights magento

This one can be a real show stopper for your Time to First Paint metric. Most of the time, your JS files are located at the very top of the document.
Which is not okay because this means the browser cannot proceed with page rendering before it can execute all these JS files first.

Here’s what you do. Move all JS files to the bottom of the <body> with the help of the following module you can create on Magento server:


di.xml


Pro tip: don’t include script tags in the <head> section. Nothing good will come of it.

You can do the same with CSS. Divide the CSS styles into two uneven parts. The smaller part will remain higher in the document. It will only contain stuff you can’t move to the bottom of the page. This is the stuff that’s crucial to page design, what the user sees immediately upon entering your page.

The bigger part will go to the very bottom of the page. The lower CSS file will contain styles that don’t affect user experience because these styles don’t affect content at the first screen of the page. This whole file shifting will unload most of the clutter from the critical render path and speed up page load.

Remote elements can also become render blockers. There are no ready-to-use solutions on how to deal with them but we can outline your options. You can either move them to your server (if you can), delete entirely (and probably get rid of a few fancy features they offered), or use preloads.

Serve Images in Next-Gen Formats

next-gen_formats pagespeed insights magento

Unoptimized images become the biggest roadblock to a fast store. Instead of indiscriminately uploading media to your store, Google Pagespeed Insights services recommend you to switch to new image formats.

Among its suggestions are JPEG 2000, JPEG XR, and WebP. All of them are more recent and offer better image compression than JPEG. Alongside the switch to new JPEG standards PageSpeed Insights algorithms recommend tinifying PNG files.

The best solution here is to use a Content Delivery Network with built-in image optimization features. Cloudflare is an obvious example with its Polish feature that can optimize and serve users the lightest version of the file without losing too much quality.

AWS users can choose Amazon Cloudfront which works well for image optimization purposes.

cloudflare_polish_on magento pagespeed insights optimization

In addition to using built in CDN features you can take an alternative route and integrate a module inside your server that can compress images for you. A bit redundant in our opinion since you’ll still need a good CDN service for other optimizations, but if that’s your call – go for it.

Minify JavaScript

minify javascript magento pagespeed insights optimization

There are a ton of JS files in Magento. In contrast to other websites, JS minification in Magento can have a significant impact on performance basically compressing files to 80-20% of their initial size.

Minify JS is fully available from Magento Admin Panel. Go to Stores > Configuration > Advanced > Developer. After you set Minify Javascript Files to YES, flush Magento cache. That’s it. This optimization is so easy that 95% of Magento stores pass the audit by default. We are writing this tip for the other 5% who haven’t got the memo.

Efficiently Encode Images

encode_images pagespeed insights magento

Much as with next-gen image format audit, this one focuses on image delivery. PageSpeed Insights services suggest you to automate your image optimization so that instead of manually making content managers, developers, and site owners compress media every time they need to upload a thing, users would just seamlessly apply compression from inside the platform.

As mentioned before in the next-gen audit, good CDNs will have image compression feature at the ready. Alternatively, you can use imagemin, libvips, Cloudinary, imgix, ImageOptim or any other tools you like to integrate image compression inside your store.

Bear in mind that Google Pagespeed only checks JPEG and BMP images in this audit. Your score is unaffected by PNG. You’ll have to account for large PNG files still slowing you down.

Remove Unused CSS

unused css pagespeed insights

This one is tricky. Unused CSS files comprise a relatively small part of what could be wrong with your store speed. For example, a general CSS file will load everything it has when your browser requests a homepage.

This file might contain styles for Checkout or Catalog. Doesn’t matter. Even if they are never used on the Homepage, you’ll have to download it.

Even though this guide lists solutions to every issue it might be too labor-intensive to improve unused CSS. You basically need to separate CSS styles by page type instead of clumping them all together. It’s kind of hard to do, to be honest. In our case, we would need to review a few hundred individual rules in order to save 80KB of data.

After everything is done, Google Pagespeed estimates a 450 ms time savings. The return on investment on this one is questionable. Clearly not a priority, that’s for sure.

Properly Size Images

proper_size_images pagespeed insights

In order to pass this Google Pagespeed audit, the difference between the image size in your browser and the actual size of the image must not exceed 25KB. The tool compares the actual size of the image and will penalize you if you upload a 2048×2048 monster to show a 256×256 pixel photo.

Most mainstream CDNs know how to handle image sizes really well so if you use one, you are already a step ahead.

Magento needs to resize the image to the right size before the browser downloads it. We will use ImageFactory image adapter in order to enable this feature.

\Magento\Framework\Image\AdapterFactory $imageFactory


This code works well for random pictures. For product images we will need a different approach. Find view.xml in the folder /etc/ located at app/design/<area>/<vendor>/<theme>/etc/view.xml.

If you can’t find one, just create it. We need to add new image size for the image we want to use. So for example if we need to use somewhere a 30×30 pixel photo, we create a new image and describe it as follows:


imageID is a unique value needed for correct association with our new image. Magento requires type=”thumbnail” to be able to use the image as a thumbnail for this type of product.

image_type_thumbnail pagespeed opportunities

This is how we can use it on a page (code example):


Here we give Magento product type and image ID.

In order to get a link to the image we need to write


Magento will resize the image and return a valid URL that you can give to the user.

Ensure Text Remains Visible During Webfont Load

webfont load pagespeed insights opportunities

You can’t make your store significantly faster with webfont load. Most often time savings will be 10-20 ms per font load. Font-display is something you should do for perceived optimization, though. Users expect to see content within 1 second of loading time. Turning on swap in CSS font-display settings can help speed up text rendering.

By default, your CSS either doesn’t have any font-display config or uses something like block which is slower.

If there’s nothing in the CSS config, this setting defaults back to auto (in fact auto means block). Swap is a superior setting in terms of speed (read more about different font-display settings here).

OK so for Magento we want to change font-display from auto to swap, the fastest possible option for text rendering. Find lib/web/css/source/lib/_typography.less and add font-display into the existing code, e.g.:


Using swap, the browser will display the second font until the first font is loaded. For example, (Monaco, Monaco Regular). Monaco Regular will be displayed until Monaco gets loaded. Since you are now using zero block and an infinite swap period, you’ll need to make sure that the two fonts look more or less the same. Oh and one more important thing. Since May 16, 2019, Google Fonts support font-display without the need to self-host them on your server.

google fonts self-host

Avoid an Excessive DOM Size

dom_size ecommerce pagespeed insights

A brand-new Magento 2 store will have 481 DOM elements which is way less than the recommended 1,500 DOM limit. The thing is, no one uses a default Magento store. Once you start customizing your store with better themes and more capable feature extensions, the number of DOM elements will begin to climb into thousands of pieces.

The number of DOM elements don’t really impact store performance but they hit page rendering speed pretty hard. This is the realm of perceived performance vs actual Magento load time.

This issue is hard to fix. The only real fix to the problem is rebuilding the store to cut down on all this clutter. It’s labor- and time-intensive. The more DOM elements you have, the better results you’ll get in the end.

For example, a 1,500+ DOM sized store took 950 ms to render and 500 ms to parse. According to our measurements, lowering the DOM size to 827 elements we managed to shave off 300 ms from the combined load (parsing+rendering). That’s not a lot. And according to UX research, improvements of less than 500 ms are not even noticeable for average users.

Compared to the complexity of the task, it’s easier to focus on more rewarding optimizations first, before you tackle this beast of a problem.

Serve Static Assets With an Efficient Cache Policy

static_cache_assets pagespeed insights magento

Cache expiration should be set to something big. If you set rarely changing files to expire frequently, the browser won’t be able to take advantage of its local cache. This is another audit where a strong CDN will help you pass easily.

The setting may look different on different platforms. This is how Cloudflare handles it:

browser_cache_expire cloudflare magento

If you for some reason don’t want to use a CDN to handle cache, make sure your Magento server is set to:

Minimize Main-Thread Work

Lots of factors here. Let’s go over each one of them and how you can make each position faster.

Script Evaluation. This is the amount of time it takes to execute JS scripts. Consider reducing the number of files that execute in the very beginning of document load. Push to the end of the HTML document as many files as you can. Use defer functionality to delay script execution that doesn’t make any difference for the user. See if you can also make the code lighter through refactoring.

Style & Layout. Render process consists of multiple steps and for each step there are different things you can do to make it shorter and faster:

  • Optimize and defer CSS files. Divide CSS into two files. Put the styles that don’t get used on the first screen to the bottom of the page. This way they will not block the initial render process and your store will look faster.
  • To speed up HTML parsing and DOM tree creation, reduce the amount of HTML code, the depth of the DOM tree elements, the number of children in each DOM element.
  • To improve render tree construction, work with CSS attributes and reduce the amount of styles.
  • To boost the performance of the layout process, make HTML files smaller. Same goes for painting.

Rendering. Webpage rendering is a non-trivial process. You can speed it up by reducing the number of CSS styles and HTML code amount.

Garbage Collection. All web browsers need to do housekeeping during regular work. This can take up a lot of time, it all depends on the store. One of the solutions is to reduce the amount of code your browser needs to execute. Our goal here is to shave off memory use. Anything goes: use less variables, refactor the code.

Script Parsing & Compilation. Common sense rules apply here. Delete unused JavaScript files, don’t load files that aren’t necessary for a specific page, minify JS.

Parse HTML & CSS. The more CSS and HTML you have, the slower parsing works. Reduce CSS and HTML amount (which basically means you need to rewrite it).

Reduce JavaScript Execution Time

reduce_JS_exec_time

Find JS files that execute at the very beginning of the page but don’t necessarily contribute to better user experience. You can safely defer their execution for a few seconds (the more code you have, the larger defer time you need to account for). Use trial and error in estimating optimal delay time.

Another approach to reducing JS execution time is to just toughen up and rewrite questionable code that slows you down.

Minimize Critical Requests Depth

chain depth magento optimization

Critical Render Chain demonstrates how your resources get loaded in the hierarchy regarding one another. Top priority files create the critical request chain that will influence the length of loading procedures before full document render.

Nesting. The more resources you have to load within one another, the bigger latency you get. Defer as many JS scripts as you can. Reduce the size of every file, wherever it’s possible. Add preload. You can get a lot done by combining these methods with one another.

Keep Request Counts Low and Transfer Sizes Small

request_counts pagespeed insights magento optimization

Number of requests. This data doesn’t directly affect the final score but will improve other metrics if you follow the recommendations. For Magento, setting a detailed budget might not be the best idea. Let’s just reiterate how you can reduce the number of requests and total file sizes.

Resource Type How to Reduce Requests How to Reduce Transfer Size
Scripts Merge JS You should minify JS, delete unused scripts, defer all JS files that you can.
Images Defer image load through lazy loading to alleviate initial flood of requests to the server. Don’t upload oversized images where smaller resolutions can do the trick.
Fonts There is such a thing as too many fonts. Get rid of some if you have too many.
Stylesheets Merge CSS files.  Minify CSS, cut out unused styles. Your goal is to only load the code that will run on this page.
Documents This section only counts barebones HTML. It’s already quite light. Not much else you can do about it.
Third-party Limit the amount of third-party services. Defer third-party file load where possible.  Review your code and delete unused third-party files or pieces.

Third-Party Usage

third-party_usage magento optimization for google score

The best defense is offence. Google Pagespeed will show you the slowest third-party files in your store. Defer or kill these scripts. And never let new files clutter your Magento store that bad ever again.

Defer Offscreen Images

defer_offscreen_images magento optimization

Every store should use lazy loading and Google unanimously announces the same approach. Lazy loading slows down offscreen image loading because users can’t actually see them when they enter the store. Everything they see is a few banners at the top and probably some text.

This is the type of content you need to load first. You can find media that needs lazy loading by hand or using a custom JS script. It’s common to just manually assign lazy loading to all media except the images on the first screen of the device.

Take into account that we are optimizing here for both mobile and desktop stores. Check how your store works in the most common mobile and desktop resolutions and make sure that you include lazy loading while keeping in mind how the store functions on different devices.

While lazy loading usually refers to images, it’s possible to use it to reprioritize the load order of JS scripts, CSS, and HTML files, too.

Offscreen image deferrance has the biggest impact on Time to Interactive (TTI).

Minify CSS

minify css in magento for google speed score

Same as Minify JS, CSS minification is a great opportunity for Magento users to easily pass another Google Pagespeed audit.

Find CSS Settings in Magento 2 Admin Panel at Stores > Settings > Configuration > Advanced > Developer.

minify magento_css

Enable Text Compression

There are 3 main tools to make text smaller. Deflate, gzip, and brotli. Deflate is basically gzip with some features missing (so we won’t mention it too much). Let’s focus on the other two then.

Gzip can archive text with 71% compress ratio. While there are more efficient solutions on the market with up to 89% compression ratios, gzip is still a great tool to save data and speed up delivery.

Brotli is another text compression alternative built into Cloudflare CDN. It offers better compression ratio and – crucially – better compression and decompression speeds. Operational speed will help pack and unpack content faster. This is a big deal for mobile devices where browsers depend on weaker mobile CPU to process archived data.

Preconnect to Required Origins

Add dns-prefetch for all remote resources. We wouldn’t expect a significant performance gain, but it’s a nice little boost to speed up your third-party assets. Magento doesn’t offer anything different here from any other platform. DNS-prefetch is easy to use and easy to implement, this is its greatest advantage.

You can also add preloading to fonts, site logo, critical CSS and JS files to get even more out of prioritizing a specific load order. Read more about preloading in the dedicated audit below.

Avoid Multiple Page Redirects

Any new redirect will make your store a bit slower. Got a new design and now need to redirect all pages from one link to another? When you create custom redirects in Magento, use 301 moved permanently instead of 302 moved temporarily.

It’s also a bad idea to change product or category URLs too much because Magento will create too many redirects inside the store. This clutter will slow down your store.

Good store management means maintaining a high housekeeping standard and eliminating links with redirects – most importantly on your critical rendering path. Google PageSpeed Insights will also penalize your score for “m.store.com”. The official guide wants you to use responsive design instead of two versions of the store.

So keep in mind that any page with two or more redirects will fail this audit.

Preload Key Requests

preload_requests magento optimization

Besides the critical render path there’s also the critical request chain. Our goal is to make this chain as short as possible. And the main method of speeding it up is to remove a few links from it. This is where preloading comes into play.

Obviously, we do preloading inside the <body>, not the <head> of the document. The idea is to load different elements at different times, deprioritizing those elements that users don’t interact with immediately after they see them.

For example, you can preload a number of things:

  • fonts,
  • styles,
  • scripts,
  • images.

Let’s say there’s a Login popup at your store. It’s pretty huge. There is a login field, a Loyalty Program feature and a large social media section.

make_account_popup magento speed optimization

You click the Login button and the popup appears. Behind the scenes the loading process prioritizes only one element of the entire popup: Sign Up Button. This is the UI element that most new users will click as soon as they see it.

Everything else – login details, social media share buttons, integrated bells and whistles – they all can wait. Sign Up button can’t. It needs to be available as soon as possible. And this is how preloading makes the entire window feel responsive and fast.

Use Video Formats for Animated Content

Some Magento stores like to use background videos on their pages. And all things considered, this is not a bad idea. Just make sure your video is actually a video and not an enormous gif.

In order to imitate gif behavior, your <video> content needs to loop continuously, have 0 volume, and play automatically without user input. Pretty simple to set up.

Video has only one disadvantage. Chrome for Android offers data saving mode. This mode will not allow the browser to load your video (but it will let the gif through). Take into account this limitation when you design for mobile user experience.

Avoid Enormous Network Payloads

avoid_payloads magento pagespeed insights

Google PageSpeed  Insighys will write you a ticket if the overall size of your resources exceeds 1.6 MB. The number centers around a slow 3G mobile connection and 10 seconds max load time. If you think about it, that’s a decent performance standard.

Ways to achieve in Magento: reduce the number of requests, defer file loading, configure compression and minification features – all the stuff we’ve already been talking about in the previous audits.

Summing Up

Google PageSpeed concentrates on frontend optimization. Just keep in mind that a fast store has a lot more going under the hood than a slow frontend.

Look into slow Magento backend & database performance, work out why the Admin Panel is sluggish. Take a look into Shopping Cart and Magento Checkout performance. Investigate how you can improve your store speed without actually raising real-life numbers (perceived performance is a thing!). These are all areas where speed matters as much as anywhere else.

If you want an expert team to run a quick and practical audit of your store and eliminate code bottlenecks – get in touch with us and we’ll be happy to help.

Magento tips from real projects
Magento tips from real projects
Close
CALL US 24/7:
Australia
& asia
+61 (02) 8005-7494