How to Optimize CSS Delivery & Defer JavaScript2019-05-07T09:55:54+00:00
  • 5 steps complete WordPress optimization guide Myhostingfacts

Optimize CSS delivery (create critical and defer unused CSS) and inline & defer JavaScript with plugin or code in function.php and .htaccess WordPress guide

Out of the box, WordPress is fast but can become slow with installing themes and a lot of plugins. Plugins are loading their own CSS and JavaScript. You can minify, combine and defer with plugins or by code in function.php.

Follow this very easy step-by-step tutorial to speed up WordPress.

Slow website leads to losing visitors and more importantly losing potential customers.

This is what you will get after optimization:

gtmetrix pagespeed, wordpress optimization, images optimization,combine internal, external, minify and defer javascript, combine thrid party CSS, minify, above the fold

These are the optimization needs to be done:

  1. Always create a child theme
  2. Above the fold (critical) CSS, combine, minify and load asynchronously
  3. Minify, combine and defer JavaScript
  4. Change size, compress and lazy load images
  5. Files expiration date or leverage browser caching
  6. Caching solution

Using WordPress means working with multiple style.css and JavaScript files not just from the theme but also from plugins (ex. Jetpack). You want those CSS and JavaScript files combined into one, minified, compressed and deferred.

How to create a child theme

Creating a child theme is a few steps with a child theme configurator plugin.

From WordPress dashboard go to tools -> Child themes and these are the steps:

1 -> CREATE a new Child Theme

2 -> Select a Parent Theme

3 -> Click Analyze

4 -> Give the child theme a name in my case (Avada-child)

5 -> Select primary stylesheet

6 -> Use the WordPress enqueue style

7 -> Optional (changes will be shown in the WordPress dashboard -> appearance -> themes

8 -> Optional (if you want to copy menus and widget from the parent theme)

9 -> Click on Create New Child Theme

10 -> Finally from WordPress dashboard go to Appearance -> Themes -> choose the new Child theme
From the Files menu in the child configurator you can include all the files you need, let’s say you want header.php never to be changed you can include in the child theme by checking it and click Copy Selected to Child Theme, this way in the further updates of the Parent theme you won’t lose any customization in the header.php. This said tho you shouldn’t ever change header.php by adding the code manually like Google Analytics but use the function.php and add the code from there into header.php. Function.php is created when you create a child theme.

The proper way to include something in header.php

 


child theme configuration plugin
child theme configuration plugin steps

The easiest way to minify, combine and defer CSS & JavaScript of WordPress is by using WP Rocket plugin

WP Rocket best caching plugin for WordPress

Recently I’ve started using WP Rocket because of how he creates above the fold (critical) CSS for every page, post, archive, author, portfolio, etc.. even for custom post types and have the best options for JavaScript defer with an option to defer jQuery too.

WP Rocket features:

  • Minify/combine HTML
  • Minify/combine CSS
  • Minify/combine JavaScript
  • LazyLoad for images
  • LazyLoad for iframes/videos
  • Optimize CSS delivery (critical CSS)
  • Defer JavaScript

All of this above can be turned on or off for every page or post etc…

This is the settings I’m using:

wp-rocket-settings-2018-12-07-5c0a61bf09179 unzip JSON file, go WP Rocket tools upload file and import settings I’m using or do it step by step by enabling settings (see images below).

WP Rocket Cache settings

WP Rocket File Optimization

WP Rocket File optimiztion

WP Rocket Media

WP Rocket settings for lazyload images and iframes with fallback image and disable WordPress emoji and embeds

WP Rocket Preload (WP Rocket will show other SEO plugin sitemaps generators if you have custom sitemap specify the URL), also you can prefetch DNS from the third party files/domains (I’m prefetching Google Fonts).

Keep in mind, you can’t fix render-blocking JavaScript from third-party apps (ex. Google fonts) or you should host them on your website, render blocking Google fonts won’t be a problem because they are cached by a big number of websites and will load so fast.

WP Rocket Preload and sitemap integration

Advanced Caching Rules: If you have cookies, login, logout, shop, check out you can finetuning to exclude cache or specify on/off cache for query strings(I don’t have any of these so left it default).

Make database backup before use database optimization (just to be on the safe side if something goes wrong)

WP Rocket CDN (the best CDN integration by far, you can choose multiple CDNs[if you have more than one CDN account] for different files)

WP Rocket CDN

WP Rocket Heartbeat (if you hit resources on your hosting you might want to reduce[all three have dropdown] or turn off[untick Controlheartbeat] heartbeat)

WP Rocket heartbeat

WP Rocket Add-Ons (turn on Google Analytics, Facebook or Varnish cache[hosting that uses it ex. WP Engine] to host the files locally[this won’t give you speed boost but satisfy Google Page insights, GTMetrix etc…])

With the plugin Autoptimize

I’ll recommend using plugin Autoptimize for combining all CSS files. Follow these steps:

After installing Autoptimize go to WordPress dashboard Settings ->Autoptimze

Click on show advanced settings (top right).

autoptimize above the fold CSS WordPress optimization myhostingfacts.com

You will see an image like this one, tick the box optimize CSS code and the box Inline and Defer CSS.

Go to critical path generator and paste your URL and click GENERATE CRITICAL PATH CSS.

above the fold, critical path css

Copy everything without <style> and </style> at the end and paste it in Autoptimize.

above the fold autoptimize fixed WordPress optimization myhostingfacts.com

From more than 1 000 000 characters it’s reduced to 15 500 (~1.5% CSS used) characters that above the fold needs to load and after it’s finished the full CSS file will be loaded asynchronously and will not render block.

With Autoptimize we combined, minified, and fixed above the fold error from Google Page Insights, the compressing which is left will be finished by enabling Gzip compression with the caching plugin.

Check Gtmetrix, Pingdom or Google page insights and see the CSS results.

Defer CSS & JavaScript manually with code in function.php

Follow the steps below to defer CSS & JavaScript and fix render blocking problem easily with code. Here if you want to do that with a plugin.

Add the code below into function.php at the end. This code will show all JavaScripts that load in the header and in the footer. After you finish with deferring the Javascript remove the code above from function.php

You will get something like this:Header:show all JavaScripts that load in the headerFooter: Choose which JavaScript file you want to defer with the following code:

jQuery is best to load in the head because a lot of plugins and themes need jQuery to load before loading some styles, front-end animations or some validation etc…

Image optimization

Image optimization can be done with plugins or with Photoshop.

True image optimization starts with size, you need to know what image size you need to your website I recommend about 1600×1200.

Limit image size to your needs.

Great plugins for image optimization:

If you have a small to medium website free version will be enough, however, they all have premium plans for unlimited1 usage.

1 They have limits depend on the plan but for one website the cheapest plan should be enough.

Using only Photoshop isn’t enough, you will end up with images too big for web usage even tho we are saving for web. Export images for web legacy with photoshop.

 Photoshop export, save for web (legacy) images optimization for wordpress blog

Worth mentioning is compress image toolur they have good options and easy to compress and change quality of pictures.

At last lazy load images. Right now I’m using the lazy-load from WP Rocket but I highly recommend using a3 lazy load plugin (a lot of good options), try to load it trough footer, if your theme doesn’t use wp_footer() use header option and defer JavaScript with Speed Booster Option or paste this code at the end of Appearance->Editor->function.php.

File expiration date (Leverage browser caching)

Can be done by a plugin or manually with .htaccess. You can skip this part if you have WP Rocket caching plugin.

Keep in mind you can’t control leverage browser caching to third-party files (ex. analytics), testing pages like Gtmetrix, Pingdom and Google page insights shouldn’t be a problem for third-party files like analytics or Google fonts because they are cached by many websites in the world.

If you have more third-party JavaScripts you should configure Google Tag Manager so the website can fetch only one header, not multiple render blocking headers.

Use far future expiry header. WordPress dashboard -> settings -> far future expiry header and enter 365 days as you can see in the picture below.

leverage browser caching, far future expiration date plugin for wordpress speed optimization

Personally, I always use the manual method .htaccess.

Go to your web hosting file manager and go to the root of your website, there will be a file .htaccess right-click opens it with editor (depend on your web hosting you may need to select and or from right to click edit). If you can’t find .htaccess you need to unhide system files.

show system files (ungide) .htaccess for leverage browser caching

ipage htaccess editing for leverage browser caching for wordpress speed

Copy this and paste in .htaccess

Caching solution (if you didn’t choose WP Rocket)

These are the top four caching plugins that you should choose from:

  1. WP Rocket
  2. WP Fastest Cache
  3. W3 Total Cache
  4. WP Super Cache

And, in the end, the most important step is choosing the right hosting. There is a lot of differences from one hosting to another. This is the list of top web hosting you should choose:

If you want to optimize CSS delivery and defer JavaScript check this post, everything explained with images.