In today's web space, site loading speed is of critical importance. It not only affects the bounce rate, but also plays an important role in positioning in search engines. One of the ways to achieve high speed is to compress assets such as CSS and JavaScript.
The WordPress CMS has a significant amount of resources, and therefore efficient and fast compression of its files becomes an important task to improve performance.
How using the Laravel Mix tool you can significantly improve the performance of your website on WordPress, and any other CMS.
Laravel Mix provides a convenient and flexible API mechanism for building Webpack for your application. In other words, it compiles and minimizes your project's resources, such as JavaScript, CSS, and images.
How to implement this procedure based on WordPress.
1. Install the necessary dependencies
First you need to install Node.js and npm, if you don't have them installed yet. Then install Laravel Mix in your WordPress project.
Open the terminal in the root folder of your WordPress site and run:
npm init -y
npm install laravel-mix --save-dev
2. Create a file webpack.mix.js
Create a file in the root directory of your WordPress sitewebpack.mix.js
. In this file, you will determine which files need to be compressed and processed.
Sample content webpack.mix.js
:
const mix = require('laravel-mix');
mix.setPublicPath('wp-content/themes/your-theme/');
mix.js('wp-content/themes/your-theme/resources/js/app.js', 'js')
.sass('wp-content/themes/your-theme/resources/sass/app.scss', 'css')
.version();
mix.minify('wp-content/themes/your-theme/public/css/app.css');
mix.minify('wp-content/themes/your-theme/public/js/app.js');
Don't forget to replace your-theme
with the name of your theme.
3. Create folders for assets
Create the following directory structure in your theme:
/wp-content/themes/your-theme/
/resources/
/js/
app.js
/sass/
app.scss
4. Configure Sass and JavaScript files
Create a app.js
and app.scss
inside the respective folders and add your styles and scripts.
5. Run the build
Assemble your files using Laravel Mix by running the following command:
npx mix
6. Connect compressed files in WordPress
Now connect the compressed files in your filefunctions.php
of your theme:
function theme_enqueue_scripts() {
wp_enqueue_style('app', get_template_directory_uri() . '/css/app.css', [], null);
wp_enqueue_script('app', get_template_directory_uri() . '/js/app.js', [], null, true);
}
add_action('wp_enqueue_scripts', 'theme_enqueue_scripts');
7. Optimization
Don't forget to check your website optimization using tools like Google PageSpeed Insights to make sure everything is working as it should.
Compression of assets is an important step towards improving the performance of your site and improving its position in search engines.