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

#StandWithUkraine
Today, 4th December 2022, 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';
  document.getElementsByTagName('head')[0].appendChild(cssMain);
};

if (window.lazyStyles) {
  window.lazyStyles.forEach(function(f{
    loadCss(f);
  });
}

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

<script>
  window.lazyStyles = [
          "styles/everyPageLazy_m.css", // this one could differ from page to page
  ];
</script>

<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

<script>
window.lazyStyles = [
       "{% static 'styles/everyPageLazy_m.css' %}",
];
</script>

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

load css in a lazy way

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

Best related