How to load css in a lazy way with universal .js file

Today, 20th March 2023, Ukraine is still bravely fighting for democratic values, human rights and peace in whole world. Russians ruthlessly kill all civilians in Ukraine including childs and destroy their cities. We are uniting against Putin’s invasion and violence, in support of the people in Ukraine. You can help by donating to Ukrainian's army.

Create js/user.js file:

function loadCss(path{
  var cssMain = document.createElement('link');
  cssMain.href = path;
  cssMain.rel = 'stylesheet';
  cssMain.type = 'text/css';

if (window.lazyStyles) {

In HTML, in the end of head section include script tag. Very important to define both defer and async attributes:

  window.lazyStyles = [
          "styles/everyPageLazy_m.css", // this one could differ from page to page

<script src="js/user.js" defer async></script>

Hashed cache compatible URLs

To bypass caching it is recommended to include filte pathes with hashes. It is task for your ssr engine. E.g. in Django you can use ManifestStaticFilesStorage and static template tag

window.lazyStyles = [
       "{% static 'styles/everyPageLazy_m.css' %}",

<script src="{% static 'js/user.js' %}" defer async></script>

load css in a lazy way

#serversiderendering #django
Bruce Hardy profile picture
Oct 20, 2020
by Bruce Hardy
Did it help you?
Yes !

Best related