Core Web Vitals - Optimizing CSS

2 min read

Why this issue happens?

Pages containing uncompressed CSS files larger than required are diminishing page speed.

Minify CSS

Ways to fix this issue

  • Instead of creating a single large CSS file, we can load different CSS files for specific purposes and devices. For instance, we might have separate CSS files for default styles, printing styles, and styles optimized for smaller devices. This approach helps tailor the styling to different contexts and improves overall performance.
<link rel="stylesheet" href="your-path" type="text/css" />
<link rel="stylesheet" href="your-path" type="text/css" media="print" />
<link
	rel="stylesheet"
	href="your-path"
	type="text/css"
	media="screen and (max-device-width: 690px)"
/>
  • Loading CSS files on a per-page basis can also be advantageous as it allows for more granular control over styling and performance. By loading CSS files specific to each page, we can tailor the stylesheets to the unique requirements of that page, optimizing performance by only including the necessary styles. This approach can help reduce the overall size of CSS files and improve loading times for individual pages.

  • Additionally, tools like Gulp, Grunt, and Webpack can be used to optimize CSS files further. These build tools offer various features such as concatenation, minification, and autoprefixing, which help streamline CSS files for better performance and maintainability. Below is the basic example of how to do with gulp.

const gulp = require("gulp");
const sass = require("gulp-sass");
const cssmin = require("gulp-cssmin");
const rename = require("gulp-rename");

function compileSCSS() {
	return gulp
		.src("src/scss/*.scss")
		.pipe(sass().on("error", sass.logError))
		.pipe(gulp.dest("src/css"));
}

function minifyCSS() {
	return gulp
		.src(["src/css/*.css", "!src/css/*.min.css"])
		.pipe(cssmin())
		.pipe(rename({ suffix: ".min" }))
		.pipe(gulp.dest("dist/css"));
}

function watchFiles() {
	gulp.watch("src/scss/**/*.scss", gulp.series(compileSCSS, minifyCSS));
}

exports.default = gulp.series(compileSCSS, minifyCSS, watchFiles);
  • Below code snippet is designed to optimize the loading and management of CSS files on a web page. It ensures that only necessary stylesheets are loaded, handles window resizing for responsive design, and initializes theme styles based on the device type, contributing to a smoother user experience
const existingStylesheets = document.querySelectorAll('link[rel="stylesheet"]');
const defaultDesktopPath = "your-desktop-css-path.css";
const defaultMobilePath = "your-mobile-css-path.css";

if (!existingStylesheets) {
	console.error("Error: Unable to retrieve existing stylesheets");
}

existingStylesheets.forEach((sheet) => {
	const sheetHref = sheet.getAttribute("href");
	if (
		sheetHref &&
		(sheetHref.includes(defaultDesktopPath) ||
			sheetHref.includes(defaultMobilePath) ||
			sheetHref.includes("your-desktop-css-path.css") ||
			sheetHref.includes("your-mobile-css-path.css"))
	) {
		const removed = sheet.parentNode.removeChild(sheet);
		if (!removed) {
			console.error("Error: Unable to remove stylesheet");
		}
	}
});

function loadCssFile(href) {
	const link = document.createElement("link");
	link.rel = "stylesheet";
	link.type = "text/css";
	link.href = href;
	link.media = "all";
	const body = document.body;
	if (body) {
		body.appendChild(link);
	} else {
		console.error("Error: document.body is null");
	}
}

function loadStylesheet(path) {
	loadCssFile(path);
}

function hasWindowSizeChanged() {
	try {
		const currentSize = window.innerWidth;
		return hasWindowSizeChanged.previousSize !== currentSize;
	} catch (error) {
		console.error("Error: Unable to retrieve window.innerWidth", error);
		return false;
	}
}

function loadThemeStyles(themePath) {
	if (!themePath || !themePath.desktop || !themePath.mobile) {
		console.error("Error: Invalid themePath", error);
		return;
	}

	const getWindowSize = window.innerWidth;

	const { desktop, mobile } = themePath;

	const loadPath = getWindowSize >= 1025 ? desktop : mobile;
	loadStylesheet(loadPath);

	hasWindowSizeChanged.previousSize = getWindowSize;
}

let initialLoadComplete = false;
let resizeTimeout;

function handleResizeEvent(event) {
	clearTimeout(resizeTimeout);
	resizeTimeout = setTimeout(() => {
		if (!initialLoadComplete || hasWindowSizeChanged()) {
			initialLoadComplete = true;
			const themePath = {
				desktop: "your-desktop-css-path.css",
				mobile: "your-mobile-css-path.css",
			};
			loadThemeStyles(themePath);
		}
	}, 50);
}

window.addEventListener("resize", handleResizeEvent, true);

loadThemeStyles({
	desktop: "your-desktop-css-path.css",
	mobile: "your-mobile-css-path.css",
});
  • We can also use the caching mechanism to cache the styles

Thanks for reading !!! 😊
Share this post :

Core Web Vitals - Analysing and Improving Web applications

Modern CSS Resets