WordPress guide how to easily defer and remove unused CSS & JavaScript by combining WP Rocket and Asset CleanUP Pro or code in functions.php and .htaccess

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.

The best performance is achieved by combining WP Rocket (for nearly everything) and Asset CleanUp Pro for unloading unused CSS, JavaScript files and easy configuration of Google fonts or locally hosted fonts. If you choose to go for the combined WP Rocket and Asset CleanUp Pro performance turn off CSS and JavaScript caching in Asset CleanUp Pro and let WP Rocket do his job.

You can use one of these two plugins and you will get great performance. You will get better performance by using WP Rocket alone compared to Asset CleanUp alone, while the best performance combined. If you don’t want to use plugins at the bottom of this tutorial I explained how to do this with code or manually with autoptimize, if you need help with code or autoptimize contact me I’ll be happy to help.

This is what you will get after optimization:

Myhostingfacts GTmetrix speed udner half sec

 

These are the optimization needs to be done:

  1. Always create a child theme
  2. Above the fold (critical), combine, minify and remove unused CSS
  3. Minify, combine and defer JavaScript
  4. Change the 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 in WordPress

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

add_action('wp_head','myhostingfacts_analytics', 20);
 
function myhostingfacts_analytics() {
?>
<script>
Google Analytics Code here

</script>
 
<?php
}

child theme configuration plugin steps

WP Rocket review: how to optimize it for best performance

WP Rocket best caching plugin for WordPress

I’ve tried every caching plugin for WordPress and no one is even close to WP Rocket. The best spent money on WordPress plugin ever.

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 and combine it with Asset CleanUp Pro for unloading ton of CSS and JavaScript.

WP Rocket features:

  • Minify HTML
  • Combine Google fonts
  • Minify/combine and create critical CSS for the front page, posts, categories, custom post type etc…
  • Minify/combine JavaScript
  • LazyLoad for images
  • LazyLoad for iframes/videos
  • Remove unused CSS (critical CSS)
  • Defer JavaScript
  • Defer jQuery
  • Easy CDN configuration

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).

WP Rocket best cache plugin for WordPress

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 best cache plugin for WordPress

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…])

WP Rocket best cache plugin for WordPress

Configuring Asset CleanUP Pro properly

Asset CleanUP Pro is a WordPress caching plugin. Beside minifying, combining and deferring CSS & JavaScript, unloading completely parts of unused CSS & JavaScript is the unique feature Asset CleanUP Pro brings to WordPress speed optimization. With Asset CleanUP Pro you can optimise global (whole website) and or overwrite per page level.

Asset CleanUP Pro unique upload CSS and JavaScript or parts of the is the most powerful feature of this WordPress plugin.

asset cleanup logo strip fat and make WordPress fast

Asset CleanUP Pro features:

  • Unload unused CSS and JavaScript files
  • Minify, combine + defer or inline CSS
  • Inline CSS for files smaller than some KB value
  • Minify, combine + defer or inline JavaScript
  • Inline JavaScript for files smaller than some KB value
  • Easy CDN configuration
  • HTML cleanup
  • Preload local fonts
  • Combine Google Fonts and load async and pre-connect

Because unloading CSS or JavaScript files can break your site Asset CleanUP Pro has a great feature called test mode which shows the changes only on a logged administrator. I recommend enabling test mode so you can learn about the theme you are using, what is required to load and what’s not.

Asset CleanUp Pro Enable test mode

These are the plugin usage preferences I’m using:

asset cleanup logo strip fat and make WordPress fast

Asset CleanUP Pro plugin usage properties

I’m not using any CDN because I’ve had big problems the Cloudflare free plan and if your website has enabled http/2 protocol server push cache can be configured only with a $200 package or up. The CDN is disabled for me if you have CDN you need to enter CDN’s CNAME/URL for the CSS and JS so Asset CleanUP Pro can cache them as static resources.

asset cleanup logo strip fat and make WordPress fast

Asset CleanUP Pro CDN configuration Myhostingfacts

These are Myhostingfacts Site-wide common site unloads:

I disabled jQuery Migrate site-wide because I’m using Avada theme and they are constantly updating it.

Asset CleanUP Pro Site-wide common unloads

HTML Source CleanUp:

Asset CleanUP Pro HTML Source CLeanUp

Avada is using icomoon.woff file to draw the social media icons the file is loading fast but and for some reason, Google Page Insights is saying that need up to 1.5sec to load. So I add the URL without the domain name to preload the font file and the Google Page Insights problem is gone and the website load faster.

asset cleanup logo strip fat and make WordPress fast

If you need to preload fonts that you host locally you need to enter the URLs of the fonts without domain name like on the picture below.

Asset CleanUp PRO local fonts

There are two main options for Google fonts either combine them and preload or remove them totally. Remove Google fonts only if you are hosting the fonts locally. The Google font URLs can be found easily in the GTmetrix waterfall section.

Asset CleanUp Google Fonts configure or remove

Disable XML-RPC:

Asset CleanUp Pro Disable XML-RPC Protocol Support partially or completely

I purposely left the Optimise CSS and Optimise JavaScript last because we are going to remove unused CSS and JavaScript before we minify, combine and defer.

This is an example of my home page but I can confidently remove unused CSS and JavaScript globally (whole site) because I know I use the same design and the same functionals for every page/post except table plugin that I’ll load only on the home page but not other pages.

asset cleanup logo strip fat and make WordPress fast

This is a good example WP Smush Pro which is a plugin for compressing and optimising images. Wp Smush Pro is a plugin that works in the WordPress dashboard and I don’t need this plugin CSS and JavaScript to load frontend so I unloaded site-wide and I removed unused CSS and JavaScript.

Asset CleanUP Pro Smush Pro unload remove unused CSS and JS

You need to know what the theme, plugins or even custom code need to load. If you don’t know the theme or plugins copy the handle name and search Google you will find what is that file doing and you will know if you need to unload or not.

asset cleanup logo strip fat and make WordPress fast

I’m giving you an image of the home page where I removed unused CSS and JavaScript with scripts I don’t need to load. I had to split into many images and the worth seeing.

Home Page Myhostingfacts Asset CleanUp Pro removed unused CSS and JavaScript first part 01 Home Page Myhostingfacts Asset CleanUp Pro removed unused CSS and JavaScript first part 02 Home Page Myhostingfacts Asset CleanUp Pro removed unused CSS and JavaScript first part 03 Home Page Myhostingfacts Asset CleanUp Pro removed unused CSS and JavaScript first part 04 Home Page Myhostingfacts Asset CleanUp Pro removed unused CSS and JavaScript first part 05 Home Page Myhostingfacts Asset CleanUp Pro removed unused CSS and JavaScript first part 06 Home Page Myhostingfacts Asset CleanUp Pro removed unused CSS and JavaScript first part 07 Home Page Myhostingfacts Asset CleanUp Pro removed unused CSS and JavaScript first part 08 Home Page Myhostingfacts Asset CleanUp Pro removed unused CSS and JavaScript first part 09 Home Page Myhostingfacts Asset CleanUp Pro removed unused CSS and JavaScript first part 10 Home Page Myhostingfacts Asset CleanUp Pro removed unused CSS and JavaScript first part 11 Home Page Myhostingfacts Asset CleanUp Pro removed unused CSS and JavaScript first part 12 Home Page Myhostingfacts Asset CleanUp Pro removed unused CSS and JavaScript first part 13

After this, we can go and minify, combine and defer CSS and JavaScript files.

This is the CSS config you should do in Asset CleanUp Pro Optimize CSS section:

note* I’m not using Asset CleanUp PRO CSS cache because I’m using the WP Rocket CSS minify, combine, and create critical(remove unused) CSS and it’s working better for me.

Asset CleanUp Pro CSS optimisation

This is the JavaScript config you should do in Asset CleanUp Pro JavaScript Optimize section:

note* I’m not using Asset CleanUp PRO in Optimize JavaScript (minify, combine and defer) section because I’m using the WP Rocket JavaScript minify, combine and defer and it’s working better for me.

asset cleanup logo strip fat and make WordPress fast

Asset CleanUp Pro JavaScript optimisation

Asset CleanUp Pro is a great WordPress caching plugin that can be used alone and get great speed but from my experience, the best is to pair it with WP Rocket, remove unused CSS and JavaScript, access the local and Google fonts and preload/pre-connect and let WP Rocket handle the caching, minifying, defer, lazy load, heartbeat, and add-ons.

asset cleanup logo strip fat and make WordPress fast

How to configure 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 (~98.5% unused CSS removed) characters that above the fold needs to load and after it’s finished the full CSS file will be loaded as not render-blocking.

WP Rocket best cache plugin for WordPress

With Autoptimize we combined, minified, removed unused CSS, 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 the 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

WP Rocket best cache plugin for WordPress

add_action( 'wp_head', 'show_scripts_in_header', 9999 );
add_action( 'wp_footer', 'show_scripts_in_footer', 9999 );
// JavaScripts appear on the top, before the headerfunction 
show_scripts_in_header(){
global $wp_scripts;echo '<pre>'; 
print_r($wp_scripts->done); echo '</pre>';
}
// JavaScripts appear on the bottom, after the footerfunction 
show_scripts_in_footer(){
global $wp_scripts;echo '<pre>';
print_r($wp_scripts->done); echo '</pre>';
}

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:

add_filter( 'script_loader_tag', 'defer_scripts_myhostingfacts', 10, 3 );
function defer_scripts_myhostingfacts( $tag, $handle, $src ) {
// The handles of the enqueued scripts we want to defer
$defer_scripts = array('here', 'is', 'an', 'example', 'change', 
'with-scripts-that-are-in-header-and-footer-from-previous-code', 
'actual-example', 'vc_woocommerce-add-to-cart-js');
if ( in_array( $handle, $defer_scripts ) ) {
return '<script src="' . $src . '" defer="defer" type="text/javascript"></script>' . "\n";}
return $tag;
}

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…

//The code below remove the scripts from head and add them in footer

function remove_head_scripts() {
remove_action(‘wp_head’, ‘wp_print_scripts’);
remove_action(‘wp_head’, ‘wp_print_head_scripts’, 9);
remove_action(‘wp_head’, ‘wp_enqueue_scripts’, 1);

add_action(‘wp_footer’, ‘wp_print_scripts’, 5);
add_action(‘wp_footer’, ‘wp_enqueue_scripts’, 5);
add_action(‘wp_footer’, ‘wp_print_head_scripts’, 5);
}
add_action( ‘wp_enqueue_scripts’, ‘remove_head_scripts’ );
//Test thoroughly if everything works

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)

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

WP Rocket best cache plugin for WordPress

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

<IfModule mod_expires.c>
ExpiresActive onExpiresDefault "access plus 1 month"
ExpiresByType text/xml "access plus 0 seconds"
ExpiresByType application/xml "access plus 0 seconds"
ExpiresByType application/json "access plus 0 seconds"
ExpiresByType image/x-icon "access plus 1 week"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType video/ogg "access plus 1 month"
ExpiresByType audio/ogg "access plus 1 month"
ExpiresByType video/mp4 "access plus 1 month"
ExpiresByType video/webm "access plus 1 month"
ExpiresByType application/x-font-ttf "access plus 1 month"
ExpiresByType font/opentype "access plus 1 month"
ExpiresByType application/x-font-woff "access plus 1 month"
ExpiresByType image/svg+xml  "access plus 1 month"
ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
</IfModule>

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

WP Rocket best cache plugin for WordPress

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.

FAQ about WordPress optimization

1. Does minifying, defer and remove unused CSS?

Yes, a lot. Deferring and removing unused CSS is also known as critical or above the fold CSS.

2. Does deferring JavaScript speed up the website?

Yes, a lot, “defer” means load everything then JavaScript also know as non-render blocking JavaScript.

3. Does hosting impact on the website load speed?

Yes, depending on the website nearly all hostings can be good. Yes, depending on the website nearly all hostings can be good. Best hosting is WP Engine closely followed by Siteground, the great balance from HostGator and great for entry websites with $23 per year iPage.

4. Do images affect website speed?

Yes a lot, images have to lazy load and be scaled down properly. “Lazy load images” term are images that load in the viewport.

5. What are the most used WordPress files for minification?

The most used files are .htaccess, header.php, footer.php, and functions.php. The proper way is to load every script in functions.php and hook the script into header and footer which means you shouldn’t be changing the actual header.php and footer.php.