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

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