Continued De-CDN (localization) of CSS library
This article is a translation of the following my article:
Original: 続 CSSライブラリの脱CDN(ローカル化)
* Translated automatically by Google.
* Please note that some links or referenced content in this article may be in Japanese.
* Comments in the code are basically in Japanese.
by bokumin
De-CDN Strategy for CSS Libraries
↓↓Continuation of this article. ↓↓
File size optimization with PurgeCSS
In a previous article, I summarized how to migrate to local management. This time, I would like to introduce how to optimize file size using PurgeCSS etc.
CSS frameworks such as Tailwind and Font Awesome contain many classes, but only a small portion of them are actually used. By using PurgeCSS, you can remove unused CSS rules and significantly reduce file size.
First, install PurgeCSS.
npm install -g purgecss
As a basic usage, it can be executed as follows.
# Tailwind CSSの最適化
purgecss --css css/tailwind.min.css --content "**/*.php" "**/*.html" "**/*.js" --output css/
# Font Awesomeの最適化
purgecss --css css/fontawesome/all.min.css --content "**/*.php" "**/*.html" "**/*.js" --safelist "fa fab fas" --output css/fontawesome/
When actually using it with OpenSUSE, do as follows.
purgecss --css /srv/www/site/css/tailwind.min.css --content "/srv/www/site/**/*.php" --content "/srv/www/site/**/*.html" --content "/srv/www/site/**/*.js" --safelist "prose max-w-none leading-relaxed hover:underline" --output /srv/www/site/css/
purgecss --css /srv/www/site/css/fontawesome/all.min.css --content "/srv/www/site/**/*.php" --content "/srv/www/site/**/*.html" --safelist "fa fab fas fa-rss fa-envelope fa-github fa-chevron-down fa-chevron-up" --output /srv/www/site/css/fontawesome/
# システムフォントでまず表示させて、後でwebフォントに切り替える場合
sed -i 's/font-display:block/font-display:swap/g' /srv/www/site/css/fontawesome/all.min.css
*The last sed command is to solve the problem of characters not being visible when loading fonts. Please run it only for those who need it
If you compare the file size before and after running PurgeCSS, you will see that the file size has decreased dramatically.
Tailwind CSS Original size 2,934,019 bytes (2.9MB) → 20,908 bytes (20KB)
Font Awesome Original size 873,256 bytes (873KB) → 45,632 bytes (45KB)
*Font Awesome is a CSS file that includes all icons, so the file size tends to be large. You can significantly reduce the weight by removing unused styles with PurgeCSS, but if you are aiming to further improve loading speed, we recommend downloading and using only the necessary icons individually.
Just by doing this, you can significantly improve the page loading speed and reduce the load on the server, so please try it if you like.
End