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';
  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

Other by Bruce Hardy