Improving Front-End Performance with Just One Line of PHP

WordPress performance

Process of improving WordPress performance: When a user visits a website, the browser needs to download all the necessary resources, such as HTML, CSS, and JavaScript, before it can render the page, this will really affect WordPress performance. This can take a few seconds, which can be a noticeable delay for users with slow internet connections.

One way to improve front-end performance is to inline CSS. This means that the CSS file is not downloaded separately, but is instead embedded in the HTML code. This eliminates the need for an additional HTTP request, which can significantly improve load times and will help improving WordPress performance.

Inline CSS

Improving WordPress Performance - inline css

On WordPress, there is a function called wp_maybe_inline_styles that can be used to inline CSS. This function takes a handle for the style and the path to the CSS file as arguments. If the CSS file is small enough, the function will inline it into the HTML code.

The size limit for the CSS file that can be inlined is 20,000 bytes. This is to prevent extremely large CSS files from being output inline, which could slow down the page.

To opt-in to inline CSS, you can use the following code:

wp_style_add_data( $style_handle, 'path', $path );

Documentation for the function here.

The style_handle is the handle used for the style, and the path is the full path to the CSS file.

If you have a right-to-left (RTL) stylesheet, you can also add support for that by using the following code:

$rtl_file = str_replace( "{$suffix}.css", "-rtl{$suffix}.css", $path );
if ( is_rtl() && file_exists( $rtl_file ) ) {
     wp_style_add_data( $style_handle, 'path', $rtl_file );
}

This code will check if the user’s browser is set to RTL mode, and if so, it will inline the RTL CSS file.

Inline CSS is a simple way to help improving WordPress performance. By using the wp_maybe_inline_styles function, you can eliminate the need for an additional HTTP request, which can significantly improve load times.

Here are some additional things to keep in mind when using inline CSS:

Benefits

  • Only inline CSS files that are small enough. The size limit is 20,000 bytes, but you may want to use a smaller limit if you have a slow internet connection.
  • Use minified CSS files. Minified CSS files are smaller and will load faster.
  • Test your changes thoroughly. Make sure that the inline CSS is working correctly before you deploy it to production.

 

By following these tips, you can use inline CSS to improve the front-end performance of your WordPress website.