Themes – WP Speed Matters https://wpspeedmatters.com Thu, 03 Feb 2022 02:49:56 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.2 https://wpspeedmatters.com/wp-content/uploads/2019/07/favicon-50x48.png Themes – WP Speed Matters https://wpspeedmatters.com 32 32 Dear WordPress Plugin/Theme Devs, You Don’t Need jQuery! https://wpspeedmatters.com/jquery-performance/ https://wpspeedmatters.com/jquery-performance/#comments Mon, 27 Jul 2020 05:22:03 +0000 https://wpspeedmatters.com/?p=3731 When I started coding in JavaScript back in 2013’s, I thought jQuery is the actual “JavaScript” and jQuery should be included in every page to execute my JS code.

But why? Because every code I copied from StackOverflow worked only after importing jQuery! 😅

What’s wrong with jQuery

jQuery is 90 KB, but when minified it’s only 32 KB.

That’s so small. A good CDN can deliver it in less than 50ms!

But it’s not about the size. jQuery has around 10k lines of code. You might not be using even 10% of it.

image 8

Every line has to be parsed and evaluated by the browser which is resource-intensive. This process affects render time, especially in mobile.

To see the actual difference, here is the same functionality written in pure jQuery and vanilla JavaScript:

jQuery:

<body>
  <div id="hello-div"></div>
  <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
  <script>
    // jQuery
    const div = $("#hello-div");

    for (let i = 0; i < 10000; i += 1) {
      div.append("<p>Hello world</p>");
    }
  </script>
</body>

Vanilla JavaScript:

<body>
  <div id="hello-div"></div>
  <script>
    // Pure JavaScript
    const div = document.getElementById("hello-div");

    for (let i = 0; i < 10000; i += 1) {
      const p = document.createElement("p");
      p.textContent = "Hello world";
      div.appendChild(p);
    }
  </script>
</body>

Here is the performance difference:

image 6
jQuery
image 7
Vanilla JavaScript

While jQuery took 2.4s, pure JavaScript only took 0.8s. That shows vanilla JavaScript is 4x faster than jQuery.

Why you don’t need jQuery

A few years back writing standard functions in vanilla JavaScript was pain and jQuery made our lives easier.

But web browsers have evolved a lot. Most of the functions that you wrote in jQuery can be written in pure JavaScript.

Here are a few examples:

1. Ajax Requests

Fetching data from a URL:

jQuery:

$.ajax({
  url: '/api.json',
  type: 'GET'
  success: (data) => {
    console.log(data)
  }
})

Vanilla JavaScript:

fetch('/api.json')
  .then(response => response.text())
  .then(body => console.log(body))

2. Find Elements & Manipulate

Find some elements from DOM (HTML) and change color:

jQuery:

<p><span>Hello</span>, how are you?</p>
<p>Me? I'm <span>good</span>.</p>

<script>
  $("p").find("span").css("color", "red");
</script>

Vanilla JavaScript:

<p><span>Hello</span>, how are you?</p>
<p>Me? I'm <span>good</span>.</p>

<script>
  document
    .querySelectorAll("p > span")
    .forEach((elem) => (elem.style.color = "red"));
</script>

3. Show/Hide Elements

Common use case of jQuery, show/hide something on click:

jQuery:

<button id="button">
  Hide me
</button>

<script>
  $("#button").click(function () {
    $("#button").hide();
  });
</script>

Vanilla JavaScript:

<button id="button">
  Hide me
</button>

<script>
  document.getElementById("button").addEventListener("click", function () {
    document.getElementById("button").style.display = "none";
  });
</script>

4. Animate

jQuery:

<button id="button" class="animate">
  Hide me
</button>

<script>
  $("#button").click(function () {
    $("#button").hide("slow");
  });
</script>

Vanilla JavaScript:

<style>
  .animate {
    opacity: 0;
    transition: opacity 0.5s ease;
  }
</style>

<button id="button">
  Hide me
</button>

<script>
  document.getElementById("button").addEventListener("click", function () {
    document.getElementById("button").classList.add("animate");
  });
</script>

You can find a lot more similar examples in:

What about Browser Support?

Most of the functions I used above are widely supported in all major browser.

It’s usually Internet Explorer and Opera Mini which doesn’t support some of them.

If you still want to support such old browsers, you can detect the browser and add polyfills. Here are a few polyfills for such common functions:

Browser support for querySelector:

image 1

Browser support for fetch:

image 2

Everyone is moving away, except WordPress

Thanks to advancement made in front-end development tools and browser support, we’re now able to drop jQuery as a dependency, but you’d never notice otherwise

Bootsrap 5 – blog post

GitHub.com also removed jQuery in 2018 – Removing jQuery from GitHub.com frontend.

While everyone has started moving away from jQuery, it’s pretty tricky in WordPress due to the vast number of plugins and themes.

From the recent blog post of Updating jQuery version shipped with WordPress:

image

WordPress should deprecate jQuery and gradually migrate to vanilla JavaScript.

You might not need JavaScript too

As I said before, the web and JavaScript is evolving fast. Similarly CSS.

Many functions which were done via JavaScript be done via CSS now. This gives another performance boost.

Some of them which can be done in pure CSS:

]]>
https://wpspeedmatters.com/jquery-performance/feed/ 3
The Tale of Removing Unused CSS from WordPress https://wpspeedmatters.com/remove-unused-css-from-wordpress/ https://wpspeedmatters.com/remove-unused-css-from-wordpress/#comments Sun, 03 Nov 2019 08:01:57 +0000 https://wpspeedmatters.com/?p=2557 When you analyze your site via Google PageSpeed Insights you might have seen the error like “Remove unused CSS”.

unused css

Ok. What is the plugin to remove unused css?!

Well, it’s not that easy.

What is Unused CSS?

Theme developers write the theme in such a way that the theme supports almost all types of sites like blog, WooCommerce, forum etc.

All these sites may require several types of HTML elements (with their own variations) like below:

  • Typography
  • Icons
  • Tables
  • Forms & buttons
  • Widgets
  • Navigation bar
  • WooCommerce
  • Author box
  • Search bar
  • Comments
  • Galleries
  • Social media buttons

The list goes on…

99% of the time, theme developers write everything into a single file style.css. Whether you use it or not, css required for all these elements are served to your users.

What if you don’t use all of these elements?

In my blog, I don’t need WooCommerce, comments (I use Disqus), and many such elements. Also, some elements like tables, forms, author box, share buttons are only needed in the posts page, not on the home page.

Well, all these are ‘unused css’.

PS: Not just themes, plugins might also be injecting extraneous css.

Why removing Unused CSS is so hard?

Dynamic Classes

You might have heard about critical path css. Critical css is the necessary styles/css required to render the above fold contents. The rest of the css is loaded in the footer (prevents render-blocking). There are several tools and plugins to extract critical css in WordPress.

However, extracting ‘used css’ is not as easy as critical css. The reason is there might be JS files that inject css classes based on buttons clicks or actions.

Try clicking on the search icon in the top of my blog, a new div and classes are injecting by JavaScript.

dynamic css class

CSS classes required for these effects are inside JavaScript and it’s very hard to find these class names. Similar case for cart page, account restricted pages etc.

Code-Splitting approach

One approach to reducing unused css (in themes) is to split the large style.css into multiple files/chunks like base.css, form.css, typography.css, table.css, comment.css etc and inject the required files in the respective pages.

Splitting files like these is easy, however, figuring which pages use which elements is extremely difficult in WordPress. Because many other plugins, custom HTML elements might be using it.

Plugins injecting CSS to unwanted pages

Some plugins developers inject all the css & js files in the pages that might not require them.

A good example is the Contact Form 7 plugin. It injects/enqueue CSS & JS files in all pages and doesn’t care whether that page contains a form or not. But there are plugins that can do this intelligently, like WP Forms.

Lazy developers right?! ?

But even if your plugin developer injects it everywhere, there are ways to remove them from the unwanted pages. We’ll cover them soon.

Is ‘unused css’ a vanity metric in Google PageSpeed?

In WordPress, removing 100% unused css is extremely tough (not impossible though).

But it’s definitely possible if you’re building a website from scratch (even if you use css libraries like Bootstrap or Tailwind). There are tools like Purge CSS that can ‘purge’ unused css during the build process. It’s so easy to setup.

Here are a few sites without unused css for example:

How to Remove Unused CSS in WordPress?

Tools to find Used/Unused CSS

Even though these can help you to find ‘used’ css or remove ‘unused’ css, it might not work well with all sites due to the ‘dynamic classes’ as I mentioned before.

If your site is mostly static and doesn’t contain many moving parts on buttons clicks give it a try.

Using Unused-css.com

Unused-css.com is another tool which can extract used css from a site. However, they’re more intelligent than the above tools. Unused-css scans your JavaScript files to see if any classes are injected by them, which fixes the ‘dynamic classes’ issue I mentioned before.

How reliable is unused-css.com?

In my case, it missed many css classes inside the JS files. Also, scheduled checks, downloading used css etc costs $25/month and their support isn’t responding to my issues. So I eventually left it.

If you want to remove 100% of your unused css, give it a try!

Once you’ve generated ‘used’ css, create a child theme, add the generated css and remove all other css!

A better, reliable approach to Remove Unused CSS in WordPress

Removing 100% unused is almost very tough in WordPress. However, you can reduce it and minimize the impact using several techniques.

Here are the steps I follow:

Analyze Unused CSS files

Lets first analyze the site to see which files have the most unused css in the corresponding page.

Note: Make sure combining/merging css is turned off.

Open Chrome Dev tools -> Coverage.

css coverage

Click ‘Start Instrumenting coverage and reload page‘ and you’ll get a report like this:

unused css and coverage

You can also click each file and see used and unused code.

Use Asset CleanUp to Remove Unused CSS files

Asset CleanUp helps you unload files from plugins and themes per page (or type of page).

asset cleanup

For example, I’ve unloaded Contact Form 7’s files from the home page. Similarly, remove the files one by one that you think is not required.

Make sure to test the site after doing this.

Generate Critical CSS

Critical CSS is the CSS that is required to render the above fold contents of the page. This is highly recommended to improve first contentful paint and first meaningful paint.

Generating critical css is much easier than generating ‘used’ css. There are several plugins like FlyingPress that can do this.

Use a CDN to deliver CSS files

A CDN can dramatically reduce the network latency and download time for CSS files (not just css, any static files). Whether your unused css files are 100KBs or 500KBs, a CDN can deliver it in <50ms.

Use a CDN like BunnyCDN or one from below:

Conclusion

Removing every single bit of unused css, I would say it’s almost impossible in WordPress!

But with the above steps, you can reduce the impact of unused css by a good percentage and improve speed and user experience.

If you can improve the FCP, FMP and TTI, Google PageSpeed Insights will also ignore these errors. See mine on mobile (on desktop, this error is not even visible):

pagespeed insights mobile score

Comment below if you’ve any queries or feedback. I read and reply to each of them within 8 hours!

]]>
https://wpspeedmatters.com/remove-unused-css-from-wordpress/feed/ 8
How to Choose a Fast Loading WordPress Theme https://wpspeedmatters.com/choose-fast-loading-wordpress-theme/ https://wpspeedmatters.com/choose-fast-loading-wordpress-theme/#comments Fri, 31 May 2019 03:02:50 +0000 https://wpspeedmatters.com/?p=1137 In quest of WordPress speed, I recently ran a poll in our Facebook Group.

Here are the results:

Screenshot from 2019 05 26 12 11 35

Choosing a fast loading WordPress theme is tricky and hard. Most of them realize that their theme is slow only after they purchase and apply it to their site.

This guide will help you with choosing a theme right before the purchase!

How to Analyze a WordPress Theme?

Let’s analyze a sample theme – Gutentype.

If you’re using ThemeForest, you’ll need to get the demo URL of the theme by going to ThemeForest -> Live Preview -> Remove Frame. Some themes might have several demos, select one.

For our sample theme Gutentype, the demo URL is https://gutentype.ancorathemes.com/.

CSS & JavaScript Size (Most Important)

Most of the themes are bloated with features, hence there will be a ton of CSS and JavaScript. Measuring CSS & JavaScript size is one of the key factors in choosing a fast loading WordPress theme. Rest of them can be optimized via some plugins/tools.

There are several tools like GTmetix, Pingdom, Google PageSpeed Insights to analyze. The tool that I recommend to analyze theme is https://www.webpagetest.org/. It allows you to analyze a site by blocking third-party scripts.

How to Check CSS & JS size?

Goto https://www.webpagetest.org/

Under the Script section, paste the following code according to your theme and click ‘START TEST’.

blockDomainsExcept gutentype.ancorathemes.com
navigate https://gutentype.ancorathemes.com/

blockDomainsExcept is the list of domains that are only allowed, in our case domain of the demo site. navigate is the URL which needs to be tested, demo theme URL.

webpagetest themeforest

Once the result is ready, go to ‘Content Breakdown’ section. You’ll see something like this:

css js analyze theme

The key factor you’ve to look into is the Bytes of CSS and JS. The lower the number, the faster the theme! Ideally, both should be under 100KB. If its’ more than 200KB, then definitely it’s bloated and will make your site slow.

Responsive Images using SRCSET

Check if your theme has srcset!

One of the key factors that affect load time in the size of images. When you upload an image of width 1000px. It’s good for desktop, but for mobile with 300px, that’s a large image. With srcset you can specify a resized image based on the device-width.

Normal images in HTML:

<img src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy">

Images with SRCSET:

<img srcset="elva-fairy-320w.jpg 320w,
             elva-fairy-480w.jpg 480w,
             elva-fairy-800w.jpg 800w"
     sizes="(max-width: 320px) 280px,
            (max-width: 480px) 440px,
            800px"
     src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy">

How to Check SRCSET?

In the demo theme, simply right-click on any image and select ‘Inspect Element’:

srcset wordpress

In case you already bought the theme, but you need responsive images to use ShortPixel Adaptive images or a CDN with image resize support.

No. of DOM Elements

Document Object Model, in simple words it’s a tree made from the HTML code.

dom elements

The number of ‘branches’ and ‘leaves’ in the tree are the DOM elements. JavaScript and CSS work using this DOM tree. The higher the number of DOM elements, slow your render time.

A poorly coded WordPress theme might have too many elements. So it’s always good to analyze the number of DOM elements in a theme.

Google recommends having the number of DOM elements below 1,500.

How to Check Dom Elements?

Go to https://developers.google.com/speed/pagespeed/insights/ and enter the demo theme URL. After analyzing check if error “Avoid an excessive DOM size” is visible.

dom elements wordpress

Why you should Ignore ‘Scores’?

Tools like GTmetrix, Pingdom, Google PageSpeed Insights are great tools to analyze a theme. However, you should not consider their scores or grades. These scores are highly depended on the no. of images, it’s size, server response time, server settings, use of CDN etc (which are theme independent).

Some Tips on Choosing Theme

Avoid ‘multi-Purpose’ Themes

Unless you have a specific need, avoid multi-purpose themes. One solution won’t fit for all. Multi-purpose themes are usually bloated with tons of features. They’ll usually make your site slow.

Choose a theme that is built for your purpose. Like themes that are specifically designed for blog, woocommerce, landing pages, forums etc.

Choose a Theme That Needs Less Plugins

With WordPress plugins you can get any feature you want, it doesn’t matter which theme you use. But be aware that these plugins may inject another set of bloated css files. So it’s better to find a theme that has most of the features you need.

Take an example, when I searched for a theme for my blog (this one), I made sure that my theme supports AMP, social sharing buttons, related posts, slider, table of contents, subscription boxes etc. If your theme has them inbuilt, they must be re-using css classes and very well optimized.

Use Filters Effectively

ThemeForest comes with handy filters. Use them effectively to find good themes. Here is I what I usually use:

themeforest filters

Tags: Responsive, Modern, Clean
Sales: High, Top Sellers
Rating: 4 stars and higher

filters themeforest

Check for Last Updated Date and Reviews

Keep an eye on the Last Updated date. Properly optimized themes will have it updated within last 60 days.

Also check out the no. of sales, comments and reviews. It will give you an overview of the theme’s quality.

seller rating themeforest

Conclusion

The theme certainly affects the loading time as well as render time. However, you should also be aware that the theme is just one factor in loading time. A good theme with tons of large images, low-performance servers can also slow down your site.

Comment below if you’ve any queries or feedback. I read and reply to each of them within 8 hours!

]]>
https://wpspeedmatters.com/choose-fast-loading-wordpress-theme/feed/ 6