Welcome to Centmin Mod Community
Register Now

WebPerf Google PageSpeed Insights – Scoring 100/100 with WordPress

Discussion in 'Web Development & Web Performance' started by eva2000, Jun 15, 2018.

  1. eva2000

    eva2000 Administrator Staff Member

    54,606
    12,225
    113
    May 24, 2014
    Brisbane, Australia
    Ratings:
    +18,794
    Local Time:
    10:42 AM
    Nginx 1.27.x
    MariaDB 10.x/11.4+
    Running speed tests with tools like Google PageSpeed Insights, WebPageTest, or KeyCDN’s site speed test are always a good way to help gauge your website’s performance. While these metrics can be very helpful it is also important to keep this data in perspective. While they can provide valuable information to help optimize your website, don’t forget about perceived performance, specifically the user’s experience. With that being said, see how we easily achieved a 100/100 score with WordPress and Google PageSpeed Insights.


    Why Care About Page Speed?


    There are a multitude of reasons why you should care about page speed. Everything from ranking higher in Google search results to providing your visitors with a better user experience, thus increasing conversions, all comes into play.

    We’ve said it before but it’s worth reiterating that as web page load times increase, so does the likelihood of your visitors bouncing. Take these statistics from Google’s industry benchmarks for mobile page speed guide:

    [​IMG]

    That same guide also goes into details regarding the page speed, page weight, and more of sites within particular industries such as automotive, technology, retail, etc. According to Google, the best practice for a website’s speed is to keep it under 3 seconds load time. As we can see from the graph below, this best practice is far from being met for sites based in the United States.

    [​IMG]

    Furthermore, as the growth of web page size continues, Google’s recommended best practice of keeping a website under 500Kb in size is also nowhere near being met, on average.

    [​IMG]

    The constant growth in web page size is likely a contributing factor to why static sites have been increasing in popularity as of late. Static sites don’t require a backend or database and are much more simple to manage. They’re also, on average, much smaller in size. Therefore if your site doesn’t require dynamic content, moving to a completely static site may drastically help improve your overall page speed and page weight. Read more about static site generators as well as how to host a static site with a CDN.

    How Page Speed Affects the Bottom Line


    As we’ve already discussed, page speed affects many areas of a website that can change (for better or worse) how much revenue your business produces online (given you are selling something). However, knowing just how much money you’re business is potentially losing out on provides a much greater incentive to then make a change.

    That’s why Google created a performance revenue calculator that estimates how much additional revenue you could be making if your site was faster. Take the example below for instance. A site which loads in 2.6 seconds, has 200,000 monthly visitors, collects an average order value of $20 and has a conversion rate of 2%. If the site owner were to improve the speed the speed of that site by just 1 second, they could potentially increase their annual revenue by almost $44,000 USD.

    [​IMG]

    That’s a fair amount of money for doing something that doesn’t take too much effort. That being said, there are a lot of different optimization suggestions out there and knowing how to implement each one can take some time. However, as mentioned in the section below, don’t base your efforts solely off of the PageSpeed Insights metrics. Your goal here isn’t too score 100/100 just for the sake of having 100/100, the goal is to improve your site’s overall performance.

    Don’t Obsess Over the 100/100 Metric[​IMG]


    A lot of people try and strive for that 100/100 score on Google PageSpeed Insights. Some do it because they are trying to speed up their site and others because a client is demanding they meet this metric (yes, this happens more than you think). It is important to take some time though and think about why we are trying to achieve that 100/100 score. Don’t think of it solely from a metrics point of view. The whole reason Google developed PageSpeed Insights was as a guideline on best web performance practices to provide recommendations to optimize your site. And by following the guidelines hopefully you will achieve a faster website.

    It is also important to remember that achieving that 100/100 might not always be possible depending upon how your environment is setup.

    WordPress and Google PageSpeed Insights


    When it comes to trying to speed up WordPress, it can sometimes be quite tricky. We all know WordPress is not the fastest platform out there, especially from a developers point of view. And the way scripts are enqueued and 3rd party plugins operate can make this somewhat of a nightmare, especially when compared to standalone frameworks. We decided to experiment with our test site and after some tweaking we were easily able to achieve a 100/100 score on PageSpeed Insights. This includes a 100/100 Speed and 100/100 User Experience score on mobile as well as a 100/100 Desktop suggestions summary.

    [​IMG]

    Here is what we did to our WordPress installation. Feel free to copy it! We are using the default Twenty Fifteen theme in our example.

    1. Optimize Images


    [​IMG]

    Google PageSpeed Insights is telling us we need to optimize our images. To fix this warning, we simply install and run the Optimus Image Optimizer plugin which is developed and maintained by KeyCDN. This plugin focuses on smart compression, which means it uses a combination of both lossless and lossy compression techniques. It has a bulk-optimization feature so after you first install it you can compress your entire media library with one click. And from there on out it will auto-compress your images upon upload. We are also using the plugin because it converts our images to .webp. This allows for even faster download times!

    [​IMG]Be aware that PageSpeed insights can show two different recommendations for image optimization, these include:

    1. Optimize Images: “Compressing … could save 4.7 KiB (30% reduction).”
    2. Optimize Images: “Compressing and resizing … could save 5.8 KiB (51% reduction).”

    The first recommendation is focussed solely towards compressing your image whereas the second recommendation is focussed on compression and resizing. If your image is too large and should be scaled down for the browser, this recommendation will be triggered. Here is more information about both PageSpeed Insights image optimization suggestions.

    2. Minify Javascript and CSS


    [​IMG]

    Google PageSpeed Insights is now telling us we need to minify our JavaScript, CSS, and HTML. To fix this problem we install the free Autoptimize plugin. In the plugin’s settings you will want to check the following:

    1. Optimize HTML Code
    2. Optimize JavaScript Code
    3. Optimize CSS Code

    We also are using KeyCDN’s free WordPress Cache Enabler plugin to deliver the .webp images we converted earlier to visitors in Chrome browsers for faster download times. In the settings make sure to check “Create an additional cached version for WebP image support.”

    [​IMG]

    3. Render-Blocking Resources Above the Fold


    [​IMG]

    Now Google PageSpeed Insights is telling us that we have JavaScript and CSS above the fold. There are three commons scenarios most people run into here, and that is your JavaScript/CSS files, Font Awesome, and Google Fonts. Fonts are render-blocking as we discussed in our case study on web font performance.

    Files


    The first issue we have to deal with is all of our Javascript and CSS files that are above the fold, making them render-blocking. To fix this we actually go back into the Autoptimize plugin we installed earlier and save the following settings.

    1. Under JavaScript Options uncheck “Force JavaScript in <head>?”
    2. Under CSS Options check “Inline all CSS?”
    Font Awesome


    Many people who use Font Awesome take the CSS file and place it in their header. The problem is that if you put this into your header, it becomes render-blocking as CSS is render-blocking. So we take the following code and we move it down to our footer, right before the </body> tag.

    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet">

    Note: Doing this will result in FOUT, which is a flash of unstyled text.

    Google Fonts


    [​IMG]The third issue is with our Google Fonts. In the WP Twenty Fifteen theme they include the Noto Serif font. By default WordPress uses a hook called wp_enqueue_scripts which loads the font in your header. This automatically results in it becoming render-blocking. To fix this we install a free plugin called Disable Google Fonts. If you are using a custom theme this might vary slightly, or you can ask your theme developer how to disable Google fonts.

    We then include our Google font with the following code in our footer, right before the </body> tag.

    <link href='https://fonts.googleapis.com/css?family=Noto+Serif:400,400italic,700,700italic' rel='stylesheet' type='text/css'>

    Note: Doing this will result in FOIT, which is a flash of invisible text.

    You could also load your Google fonts asynchronously by using Google’s Web Font Loader. Simply place the following code below in your footer.

    <script type="text/javascript">
    WebFontConfig = {
    google: { families: [ 'Noto+Serif:400,400italic,700,700italic' ] }
    };
    (function() {
    var wf = document.createElement('script');
    wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
    wf.type = 'text/javascript';
    wf.async = 'true';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(wf, s);
    })(); </script>

    [​IMG]

    4. Leverage Browser Caching


    [​IMG]

    Files


    Now we are receiving a warning about leveraging browser caching. We are using KeyCDN, deployed with our free WordPress CDN Enabler plugin, and this means that any assets delivered from the CDN already have cache-control headers. However with the Twenty Fifteen theme there was one file which wasn’t getting delivered with the CDN. To fix this we simply add cache-control headers to our origin server by adding the following code to our .htaccess file.

    <filesMatch ".(ico|pdf|flv|jpg|svg|jpeg|png|gif|js|css|swf)$">
    Header set Cache-Control "max-age=84600, public"
    </filesMatch>

    And here is the code if you are on a Nginx server.

    location ~* \.(js|css|png|jpg|svg|jpeg|gif|ico)$ {
    expires 2d;
    add_header Cache-Control "public, no-transform";
    }
    Google Analytics


    [​IMG]

    Another issue we run into is with Google Analytics. Funny thing is that this is a warning from their own script. http://www.google-analytics.com/analytics.js. The problem occurs because their script has a cache lifetime of only 2 hours. Google has already said that they won’t fix this. Which leaves almost everyone running analytics with a warning that they cannot fix. The most frustrating part of this is probably for people that deal with clients asking for Google PageSpeed Insights improvements. Telling a client you can’t fix something because Google won’t let you in their own tool sounds a little crazy.

    A solution would be to host a local version of analytics.js. Google doesn’t recommend this but if you setup a script to grab the latest version it probably wouldn’t be an issue. There is free WordPress plugin called Host Analytics.js Locally which sets up a cron job to sync across periodically the latest version of analytics.js. This then also allows you to serve it from your own CDN, such as KeyCDN. This will get rid of the “leverage browser caching” warning with Google Analytics.

    [​IMG]

    Read our in-depth post on how to host Google Analytics locally.

    5. Enable Compression


    We already had Gzip enabled on our origin server and by default Gzip is enabled on all KeyCDN edge servers from where assets are being delivered. Below are instructions if you need to enable it on your origin server.

    Apache


    You can enable compression by adding the following to your .htaccess file.

    <IfModule mod_deflate.c>
    # Compress HTML, CSS, JavaScript, Text, XML and fonts
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
    AddOutputFilterByType DEFLATE application/x-font
    AddOutputFilterByType DEFLATE application/x-font-opentype
    AddOutputFilterByType DEFLATE application/x-font-otf
    AddOutputFilterByType DEFLATE application/x-font-truetype
    AddOutputFilterByType DEFLATE application/x-font-ttf
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE font/opentype
    AddOutputFilterByType DEFLATE font/otf
    AddOutputFilterByType DEFLATE font/ttf
    AddOutputFilterByType DEFLATE image/svg+xml
    AddOutputFilterByType DEFLATE image/x-icon
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/javascript
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/xml

    # Remove browser bugs (only needed for really old browsers)
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
    Header append Vary User-Agent
    </IfModule>
    Nginx


    You can enable compression by adding the following to your nginx.conf file.


    gzip on;
    gzip_comp_level 2;
    gzip_http_version 1.0;
    gzip_proxied any;
    gzip_min_length 1100;
    gzip_buffers 16 8k;
    gzip_types text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_disable "MSIE [1-6].(?!.*SV1)";
    gzip_vary on;

    [​IMG]

    6. Reduce server response time


    And finally, the reduce server response time warning. The best recommendations for this is to use a fast web host and also implement a CDN, such as KeyCDN.

    And that’s it! If you were able to follow everything above you should now have a 100/100 in Google PageSpeed Insights with your WordPress site.

    [​IMG]

    7. Remove Query Strings – Optional Step


    Another thing we recommend is to remove query strings from your static resources. Resources with a “?” in the URL are not cached by some proxy caching servers or CDNS, which could result in a large missed opportunity for increased speeds. One way to do this would be to add the following to your functions.php file.

    function _remove_script_version( $src ){
    $parts = explode( '?ver', $src );
    return $parts[0];
    }
    add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );
    add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );

    Another option would be to install a free plugin like Remove Query Strings From Static Resources.

    [​IMG]

    This plugin removes query strings from your static resources like CSS and JavaScript files. It will improve your cache performance and overall score in Google PageSpeed Insights, YSlow, Pingdom and GTmetrix. Just install and forget everything, as there is no configuration needed. But make sure to clear your cache after installing this plugin.

    Before and After


    So does the 100/100 actually help us achieve a faster page speed? In fact, all of the optimizations we applied per Google PageSpeed Insights recommendations did decrease our load time. We thought we had a pretty fast site already, but manually going through each one of these and treating them like a checklist did shave off some additional time. See the difference below.

    Before Google PageSpeed Insights Recommendations


    We used both Pingdom and WebPageTest to show you the before and after. Remember, Pingdom doesn’t yet support HTTP/2. But some people still prefer seeing these tests as they have easier to understand metrics. We ran the tests five times and got a median as usual.

    Pingdom


    [​IMG]

    WebPageTest


    [​IMG]

    After Google PageSpeed Insights Recommendations

    Pingdom


    [​IMG]

    WebPageTest


    [​IMG]

    Here is a comparison of the results.

    Testing Tool Before (s) After (s) DIFFERENCE %
    Pingdom
    0.328​
    0.277​
    – 15.55%
    WebPageTest
    1.839​
    1.537​
    – 16.42%​

    As you can see the total download time decreased on average around 15-16% by following all of the Google PageSpeed recommendations. We are also able to get rid of 9 HTTP requests, although this becomes less important with HTTP/2. Note: We were serving .webp images before and after.

    Google PageSpeed Insights – In Summary


    As you can see the recommendations from Google PageSpeed Insights are valuable and if followed can help optimize your site. Again, we don’t recommend obsessing over these numbers. If you can’t score a 100/100 it isn’t the end of the world. Our best advice is to simply implement as many optimizations as you can in your individual environment. And don’t forget to test for user experience. Just because a tool says your site loads fast, it could be the exact opposite experience for an actual person browsing your site.

    We also highly recommend reading our complete guide on how to speed up WordPress which contains additional optimization tips. The PageSpeed Insights team also recently launched a new website speed test tool on “think with Google” which you might want to check out. One nice feature is the beautiful reports that it generates. Can be great for sending to clients.

    Related Articles


    The post Google PageSpeed Insights – Scoring 100/100 with WordPress appeared first on KeyCDN Blog.

    Continue reading...
     
    Last edited: Jun 25, 2018
  2. Mrbo

    Mrbo Member

    113
    7
    18
    Jun 17, 2018
    Ratings:
    +7
    Local Time:
    7:42 AM
    Hi! Thanks for this tutorial.

    Where do i put this code:


     
  3. eva2000

    eva2000 Administrator Staff Member

    54,606
    12,225
    113
    May 24, 2014
    Brisbane, Australia
    Ratings:
    +18,794
    Local Time:
    10:42 AM
    Nginx 1.27.x
    MariaDB 10.x/11.4+
    Centmin Mod already has those settings by default globally for all nginx vhosts in staticfiles.conf include file and nginx.conf