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) {
  window.lazyStyles.forEach(function(f) {

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 templatetag

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

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

#serversiderendering #django
menu 15
Bruce Hardy profile picture
Oct 20, 2020
by Bruce Hardy

Best related

Other by Bruce Hardy