shinsenter / defer.js

🥇 A lightweight JavaScript library that helps you lazy load (almost) anything. Defer.js is dependency-free, highly efficient, and optimized for Web Vitals.
https://shinsenter.github.io/defer.js/
MIT License
277 stars 45 forks source link

Defer.all for CSS files? #102

Closed peixotorms closed 2 years ago

peixotorms commented 2 years ago

Hello,

I see we can target all scripts by type with Defer.all but is there something like that available for css files? How can I defer multiple css files by type, class or some other attribute?

Right now I am using something like:

document.querySelectorAll('link[rel="defer-css"]').forEach(function(a){Defer.css(a.getAttribute("href"),a.getAttribute("id"))}) but would be great if I could just do Defer.all('link[type="defer-css"]');

Thank you

shinsenter commented 2 years ago

Hey @peixotorms

The original design of this library was mainly to lazyload media tags and script tags. You can also use it to lazyload style or link tags using their media attribute as a trick.

<link rel="stylesheet" href="mydesign.css" media="screen and (max-width:1px)" data-media="all" />
<style media="screen and (max-width:1px)" data-media="all">/* inline css */</style>
Defer.dom('[data-media]');

However, I'm not sure this will give a good user experience, as lazyloading stylesheet tags can cause elements on the web page to jerk or shift.

peixotorms commented 2 years ago

Thank you for the reply, that was useful!

There is still good experience if you are lazy loading stylesheets that are not on the critical path. For example, let's say you have font awesome icons only in the footer. Instead of loading a large CSS file render blocking, or using network resources loading it async, we can load it on interaction. That is when, Defer.dom('[data-media]'); will come in handy, or for example when we want to inject a css file on a click for some sort of ondemand experience.

Thanks