July 19, 2024
Suppose you’ve noticed that your site is taking a bit too long to load. More often than not, the problem lies in its code. Whether it’s Cascading Style Sheets (CSS) or JavaScript (JS), it has to be optimized so the code can be processed faster.
Doing so will instantly give a boost to your site’s speed and improve its performance as well. Having said that, there are many ways to go about this.
In this article, we’ll cover most of them so if you want to learn how to optimize CSS and JS for speeding up your site, read on.
Below, we’re going to discuss the different ways in detail so you can understand better. An example will also be provided for each one.
Minification is the process of removing all the unnecessary things from a code without changing its functionality. These things mainly include the characters, whitespaces, and comments.
This reduces the size of your website code and the servers take less time processing it, resulting in faster load speeds. Having said that, you can minify your code manually by removing the aforementioned things. However, the manual process is only recommended when the original code isn’t too long.
Website codes, whether CSS or JS are usually quite long, and manual minification isn’t suggested for them. This is because there are huge chances of errors and it’ll just take a lot of your time. Therefore, it’s best if you just run your site’s code through a tool like Minifier.org to automate the process. We personally do this as well whenever the need arises.
To exemplify minification, below are examples for both CSS and JS. It is worth mentioning that we used the said tool to generate these examples.
CSS Minification Example
Original CSS Code:
/* This is a comment */
body {
background-color: white;
font-size: 16px;
}
Minified CSS:
body{background-color:white;font-size:16px;}
JavaScript Minification Example
Original JavaScript:
// This is a comment
function add(a, b) {
return a + b;
}
Minified JavaScript:
function add(a,b){return a+b;}
Concatenation is to attach two strings to make a single long one. Combining multiple CSS and JS files into one file each can reduce the number of HTTP requests.
The fewer number of HTTP requests are received, the better the site speed will be. While concatenation can be done manually using the “concat()” method, it is not recommended on large codes. This is simply because too much time will be required and you’ll be frustrated by the end.
A better way is to use a tool like Gulp that can automate this process. That said, here’s what a concatenated JS code looks like using Gulp.
Example with Gulp
const gulp = require('gulp');
const concat = require('gulp-concat');
gulp.task('concat-css', function() {
return gulp.src('src/css/*.css')
.pipe(concat('styles.css'))
.pipe(gulp.dest('dist/css'));
});
gulp.task('concat-js', function() {
return gulp.src('src/js/*.js')
.pipe(concat('scripts.js'))
.pipe(gulp.dest('dist/js'));
});
Asynchronous loading allows certain things like images or scripts of a webpage to be loaded in the background while the rest of the elements continue to load as well. This way, the rendering of the page won’t be hindered and the overall speed of your site will improve.
To load JavaScript asynchronously, use ‘async’ or ‘defer’ attributes. What these attributes will do is the first one will signal the browser to download the script while the page is rendering without waiting for the download to be completed.
The second attribute we mentioned instructs the browser to download the script in the background after some delay or wait until the page has finished rendering before executing the script and user has interacted with the page.
Below is an example JS code that showcases the use of both attributes for asynchronous loading.
Async JavaScript
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
This code is an example of loading a Google AdSense script asynchronously.
Defer JavaScript
<script defer src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
This code is an example of loading a Google AdSense script deferred.
Inlining small CSS and JavaScript means including the code directly within your HTML file instead of linking to external files. This is done by placing CSS code within the relevant HTML tag as an attribute.
Having said that, if you inline small CSS and JS snippets that are essential for rendering above-the-fold content into your site’s HTML, its loading speed and performance can be increased since the number of HTTP requests and additional round trips will be lowered.
To exemplify this, an inlined CSS code is provided below.
Inlined CSS
<h1 style="size:48px; color:#fff; margin: 10px;"> HELLO WORLD </h1>
JavaScript and CSS files usually include the scripts and styling of the whole website. It can just so happen that the page the user is trying to load uses only a small portion of that file. To ensure maximum speed, it is important to remove all the unnecessary scripts needed to load a particular page. This is because the unused snippets of code won’t have to be executed in the background.
Having said that, for CSS, a tool like PurgeCSS can work well and automate the process of removing unused strings. Conversely, for JavaScript, Webpacks’ tree-shaking feature is great.
To install and configure the plugins of these two tools, enter the following codes and your site’s unused CSS and JS will be removed.
Unused CSS Removal with PurgeCSS
Installation:
npm install @fullhuman/postcss-purgecss
Configuration:
// postcss.config.js
const purgecss = require('@fullhuman/postcss-purgecss')({
content: ['./**/*.html'],
defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
});
module.exports = {
plugins: [
purgecss,
require('autoprefixer'),
]
};
Unused JS Removal with Webpack
Configuration File:
// webpack.config.js
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: __dirname + '/dist'
},
optimization: {
usedExports: true,
},
};
These are the ways to optimize CSS and JS to give a boost to your site’s speed. With everything discussed, our post comes to an end.
When the need for website speed-up arises, you might have to optimize its code. Whether it’s in JavaScript or Cascading Style Sheets, optimizing isn’t an easy task. There are many ways to do it and in this article, we have discussed each one in detail so you can do it yourself easily. We’ve also mentioned some tools that can automate each way for assistance.