Op-edAsync CSS and removing blocking CSS resources from your website

Async CSS and removing blocking CSS resources from your website

Slow website connectivity can discourage users, with up to 40% choosing not to revisit your site unless alternatives are unavailable. Several factors contribute to slow website loading, such as the possibility that certain CSS and JavaScript elements hinder HTML page rendering.

A slow website not only dampens the user experience but also adversely affects search engines like Google. Over time, your website may disappear from Google’s search results due to poor user experience and connectivity issues. Google offers a Speed Test Tool called Google Speed PageInsights, which helps identify issues and assesses user experience quality. Google evaluates your website based on server response, device compatibility, caching, and various other factors.

To enhance your website’s performance, consider optimizing async CSS and removing blocking CSS resources.

The common reasons behind your website’s slow loading include:

  • Extensive use of JavaScript and CSS
  • Utilizing multiple external CSS and JavaScript files
  • Large page size and the number of images used
  • Type of server-side scripting language
  • Extensive use of server-side scripting languages, etc.

Google recommends using the async attribute with JavaScript, and while this isn’t directly applicable to CSS, there are techniques to achieve async CSS loading. In this article, we provide a detailed explanation of how you can make your CSS files load asynchronously for improved website performance, particularly in the context of WordPress async CSS.

Step 1- Include CSS in “NoScript” tag

Include all those CSS files under the <noscript> tag which you want to async and are blocking the CSS resources. With the use of following source code you will be able to increase the rating of your website in Google Speed Insight:
Your page has 1 blocking script resources and 10 blocking CSS resources. This causes a delay in rendering your page.

<noscript id="async-css">
 	 	 	 	<link rel="stylesheet" type="text/css" href="example.css"/>
 	 	 	 	<link rel="stylesheet" type="text/css" href="example_style.css"/>
 	 	 	 	<link rel="stylesheet" type="text/css" href="//thirdparty.tl/example.css"/>
</noscript>

Step 2- Handling CSS blocking – Using CSS as Async

Add following JavaScript code at the bottom of your HTML file before </body> tag. This JavaScript source code fires when the HTML file completely loads on the user’s web browser. This code basically calls i.e. imports all the CSS files including the parent domain and third party websites included under <noscript> tag in the Step 1.

<script>// <![CDATA[ var loadDeferredStyles = function() { var addStylesNode = document.getElementById("async-css"); var replacement = document.createElement("div"); replacement.innerHTML = addStylesNode.textContent; document.body.appendChild(replacement) addStylesNode.parentElement.removeChild(addStylesNode); }; var raf = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame; if (raf) raf(function() { window.setTimeout(loadDeferredStyles, 0); }); else window.addEventListener('load', loadDeferredStyles); // ]]></script>

An Example of CSS and JavaScript Async

Here is an example of async load of CSS with the help of JavaScript with the complete HTML tags.

<!DOCTYPE html>
 <html>
<head>
<meta charset="UTF-8">
<title>IsrgRajan.com</title>
<noscript id="async-css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
</noscript>
</head>

<body>
Content of the document......

<script>
var loadDeferredStyles = function() {
var addStylesNode = document.getElementById("async-css");
var replacement = document.createElement("div");
replacement.innerHTML = addStylesNode.textContent;
document.body.appendChild(replacement)
addStylesNode.parentElement.removeChild(addStylesNode);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame ||
webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) raf(function() { window.setTimeout(loadDeferredStyles, 0); });
else window.addEventListener('load', loadDeferredStyles);
</script>
<script async src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</body>
</html>

Async CSS in WordPress

To asynchronously load CSS in WordPress using the Autoptimize WordPress plugin, follow these steps:

  1. Install and Activate Autoptimize Plugin: Begin by installing and activating the Autoptimize plugin from the WordPress Plugin Directory.
  2. Access Autoptimize Settings: Navigate to the WordPress Dashboard, go to “Settings,” and select “Autoptimize.” This will take you to the Autoptimize plugin settings page.
  3. Enable CSS Optimization: On the Autoptimize settings page, locate the “CSS Options” section. Enable the “Optimize CSS Code” option to initiate the CSS optimization process.
  4. Enable Async CSS: Scroll down to find the “Extra” settings within the CSS Options. Enable the “Inline and Defer CSS?” option. This will automatically defer the loading of CSS, making it asynchronous.
  5. Review Additional Settings: While in the Autoptimize settings, you can review and adjust other options based on your specific requirements. Consider experimenting with different settings to optimize your website’s performance.
  6. Save Changes: Once you’ve configured the settings to include async CSS loading, scroll to the bottom of the page and click the “Save Changes and Empty Cache” button. This ensures that the changes take effect immediately.
  7. Verify Async CSS Loading: To confirm that the async CSS feature is active, you can inspect your website’s source code or use browser developer tools. Look for the “async” attribute in the CSS script tags, indicating that the CSS is loading asynchronously.

By following these steps, you’ve successfully implemented async CSS in WordPress using the Autoptimize plugin. This approach enhances your website’s performance by optimizing CSS loading, contributing to a faster and more responsive user experience.

To add the async attribute to CSS files in WordPress, you can use a custom function along with the style_loader_tag filter. Here’s an example of how you can achieve this:

// Define a custom function to add async attribute to CSS files
function add_async_attribute_to_css($tag, $handle) {
// Specify the handles of CSS files to which you want to add async
$async_css_handles = array('your-css-handle-1', 'your-css-handle-2');

// Check if the current handle is in the array of async CSS handles
if (in_array($handle, $async_css_handles)) {
// Add the async attribute to the tag
$tag = str_replace(' rel=', ' async="async" rel=', $tag);
}

return $tag;
}

// Hook the custom function to the style_loader_tag filter
add_filter('style_loader_tag', 'add_async_attribute_to_css', 10, 2);

In this example, replace 'your-css-handle-1' and 'your-css-handle-2' with the actual handles of the CSS files you want to load asynchronously. You can add more handles to the $async_css_handles array as needed.

This function hooks into the style_loader_tag filter, which allows you to modify the HTML output of the <link> tag for stylesheets. The async attribute is added to the specified CSS files, enabling asynchronous loading.

Add this code to your theme’s functions.php file or create a custom plugin. Always remember to test any code modifications on a staging site before applying them to a live website.

Async CSS and JavaScript using Rocket Loader

Another, most affordable and easy method to enable async CSS and async JavaScript and remove blocking CSS and JavaScript from your website is by using the Rocket loader features that come free of cost with Cloudflare CDN. You can sign up for a Cloudflare account for free and can use it as a CDN at no cost, and that’s with all DNS features. To enable Rocket loader, simply log in to your Cloudflare dashboard, navigate to the “Speed” section, and activate the “Rocket Loader” feature. This powerful tool enhances your website’s performance by automatically optimizing and loading scripts asynchronously.

Hope you will find it useful in not only increasing the Google Speed Insight rating, but also loading your website without blocking the resources.

IR Media Team
IR Media Team
IR Media Team is a member of Digital Pradesh News Networks, a collective of journalists, reporters, writers, editors, lawyers, advocates, professors, and scholars affiliated with the Digital Pradesh News Networks.

Latest Updates