https://idea-hack.com/blog/107043/

Eliminate render-blocking resources for WordPress

Learn how to eliminate render-blocking css for WordPress. If done properly, Google Page Speed Insight can significantly improve its reputation.

What are the render-blocking resources?

WordPress is operated by running multiple plugins and themes by numerous developers.

It’s not unusual for all 30 plugin developers to be different people when you run 30 plugins.

In that case, the total number of files loaded on the site can exceed 100.

If the page loads 100 files , this will make 100 requests to the server.

The loading of the web page is not considered complete until all of them are completed.

The resources obtained by these 100 requests hinder the display (rendering) of the site each time and are called “render-blocking resources.”

If you leave this unchecked, Google Page Speed Insight’s rating will drop, and the page loading speed will be affected, so I want to improve it.

Eliminate render-blocking CSS resources for WordPress

It would be best if you now understood the need for asynchronous CSS. In the case of CSS, it is adequate to write the main CSS inline and load all external CSS files into the perineum.

However, in the case of a WordPress site where the code of an unspecified number of developers is mixed, if you want all CSS to be processed asynchronously, the following must be assumed.

  • It would be best if you didn’t change the CSS loading order.
  • It would be best if you didn’t tweak the CSS loading position.
  • It would be best if you didn’t try to reduce the number of requests by combining multiple CSS files into one.

If your site is entirely built with your code, there are cases where it is safe to ignore these assumptions. Even so, you should adhere to these assumptions, unless you are an advanced WordPress developer.

Let’s get started.

Make the main css files inline

If your theme is not created by yourself, it may not be very easy to apply it, but if you proceed with this method, you can write essential CSS files inline.

This time we will load Bootstrap4 inline.

How to get CSS file in WordPress and output as inline styleBy acquiring a CSS file with WordPress and outputting it as an inline style, you can expect to improve the score of Google Page Speed Insight.
Step 1
Prepare a function to compress CSS
PHP
<?php
compress_css_code( $code ) {
		// Remove Comments
		$code = preg_replace( '!/*[^*]**+([^/][^*]**+)*/!', '', $code );
		// Remove tabs, spaces, newlines, etc.
		$code = str_replace( array( "rn", "r", "n", "t", '  ', '    ', '    ' ), '', $code );
		return $code;
	}
?>

First, prepare a function to compress the CSS file. It can be applied not only to CSS but also to Javascript.

 
Step 2
Prepare a function to read and compress CSS
PHP
<?php
generate_bootstrap_css() {
		$output = file_get_contents( get_template_directory_uri().'/library/bootstrap/css/bootstrap.min.css', true );
		return compress_css_code( $output );
	}
?>

This function reads the Bootstrap file in your theme and returns a compressed version of this.

 
Step 3
Write inline CSS using WordPress functions
PHP
<?php
wp_register_style( 'bootstrap', false );
wp_enqueue_style( 'bootstrap' );
wp_add_inline_style( 'bootstrap', generate_bootstrap_css() );
?>

First, I use the code wp_register_style ('bootstrap', false); to register a handler named “bootstrap”.

Then I write the code wp_enqueue_style ('bootstrap'); to enqueue the handler.

Finally, I use the code called wp_add_inline_style ('bootstrap', generate_bootstrap_css ()); to execute the function prepared up to Step 2, and read in all Bootstrap’s CSS code inline.

 

You have successfully written all the Bootstrap CSS code inline.

Change render-blocking CSS resources to asynchronous processing

The following three media attributes of the link tag exist.

Link media attribute
all

CSS used both when printing and displaying on a web page.

screen

CSS used only when in use on a web page only.

print

CSS used only when printing only.

By using this property, the value of all media attributes is set to “print “when loading the page.

And by changing it to “all” after the page loading is completed.
This makes it possible to make CSS loading asynchronous.

How to change all external CSS files to asynchronous setting in WordPressWordPress loads a lot of CSS, but they block rendering, which negatively impacts Google Page Speed Insight scores. In such a case, let the CSS process asynchronously.
Step 1
Prepare a function to change all CSS to asynchronous processing
PHP
<?php
replace_link_stylesheet_tag( $html, $handle, $href, $media ) {
      return preg_replace( array( "/'/", '/(media)=".+?" */' ), array( '"', 'media="print" onload="this.media='all'"' ), $html );
    }
?>

Unfortunately, WordPress does not provide a convenient way to control media attributes directly. Therefore, using the "pre_replace" function and regular expressions, rewrite the link tag using code.

 
Step 2
Hook to style_loader_tag
PHP
<?php 
if ( ! is_admin() ) {
add_filter( 'style_loader_tag', 'replace_link_stylesheet_tag', 10, 4 ); 
} ?>

The style_loader_tag hook is a hook that is “prepared to add any customize just before the link tag is output on the page.”

Four arguments are available. See below for details

style_loader_tag
 

Eliminate render-blocking JavaScript resources for WordPress

In the case of JavaScript, it is recommended not to delay some files that depend on the inline script, but to delay other external JavaScript files.

However, in the case of a WordPress site where the code of an unspecified number of developers is mixed, the following must be assumed when deferring all JavaScript files.

  • It would be best if you didn’t change the JavaScript loading order.
  • It would be best if you didn’t tweak the JavaScript loading position.
  • It would be best if you did not try to reduce the number of requests by combining multiple JavaScript files.
  • JavaScript should not be inline loaded

If your site is entirely built with your own code, there are cases where it is safe to ignore these assumptions.

Even so, you should adhere to these assumptions, unless you are an advanced WordPress developer.

Let’s get started.

Why you should not write JavaScript inline

If the JavaScript file is not lazy-loaded, the JavaScript file and the inline script will be loaded in order.

On the other hand, if the JavaScript file is lazy-loaded, the inline script will be executed first. For example, there are many cases where an inline script that assumes the loading of jQuery is executed before loading jQuery.

Lazy loading JavaScript

There are two ways to configure lazy loading in JavaScript. One is to use the defer attribute and the other is to use the async attribute.
I strongly recommend using the defer attribute.

Difference between defer attribute and async attribute
defer attribute

When the loading of the DOM is complete, the source will load “in order from the javascript file written in HTML document.”

async attribute

When the loading of the DOM is completed, “Load the JavaScript file regardless of the order on the source” (asynchronous)

How to eliminate render-blocking javascript resources for WordPressRemove render-blocking javascript resources for WordPress, and improve page load speed and Google Page Speed Insight evaluation.
Step 1-1
Prepare a function to add delay processing to all JavaScript (all)
HTML
<?php
function replace_link_script_tag( $tag, $handle, $src ) {
  return preg_replace( array( "/'/", '/ type="text/javascript"/' ), array( '"', ' type="text/javascript" defer' ), $tag );
  break;
}
?>

Select here to add asynchronous processing to all JavaScript

 
Step 1-2
Prepare a function to add delay processing to all JavaScript (except jQuery)
HTML
<?php
function replace_link_script_tag( $tag, $handle, $src ) {
  //Format Change
  switch ( $handle ) {
    case 'jquery-core':
      // code...
      return $tag;
      break;
    default:
      // code...
      return preg_replace( array( "/'/", '/ type="text/javascript"/' ), array( '"', ' type="text/javascript" defer' ), $tag );
      break;
  }
}
?>

If there is at least one inline script that assumes jQuery loading, the code in Step 1-1 will always cause a problem.

Therefore, I recommend this code, which defer scripts except for jQuery.
If there is code other than jQuery that should not be deferred, check the value of $handle passed as an argument and add exclusion settings.

 
Step 2
Hook to script_loader_tag
HTML
<?php
if ( ! is_admin() ) {
  add_filter( 'script_loader_tag', 'replace_link_script_tag', 10, 3 );
}
?>

The script_loader_tag hook is a hook that is “prepared to execute any customize just before the script tag is output to the page.”

There are 3 arguments. See below for details.

 

Conclusion

In this way, you can improve performance by writing necessary CSS inline and setting all other render-blocking CSS resources to asynchronous processing.

There is no need to change the loading order of CSS defined by each plugin, and display collapse is unlikely to occur.

And by setting lazy loading for the Javascript files, it is possible to eliminate render-blocking resources.

However, it is recommended to exclude JavaScript files that depend on inline scripts, such as jQuery, because javascript that is loaded inline will be loaded first.

未分類