Delay The Loading Of Anything With Defer.js

Delay The Loading Of Anything With Defer.js

Defer.js is a small and lightweight JavaScript library that delays the loading of web resources to improve page speed.

Supports JavaScript, CSS, Images, Iframes, Video, Audios, and any DOM you can imagine.

How to use it:

1. Load the minified version of the defer.js library in the document.

<script src="defer.min.js"></script>

2. Defer the loading of JavaScript within the document. In this example, the target script will wait for 3 seconds to load after the page is fully loaded. The second parameter is used to append a unique ID to the script.

// Defer.js(src, id, delay, callback)
Defer.js('target.js', 'target-id', 2000, function() {
  // do something

// Or
<script type="deferjs" src="1.js"></script>

3. Defer the loading of CSS within the document.

// Defer.css(src, id, delay, callback)
Defer.css('target.css', 'target-id', 2000);

4. Defer the loading of any DOM elements (like images, iframes, videos, audios, etc) within the document.

// Defer.dom(selector, delay, cssclass, validate, observeOptions)

// lazy load images with the CSS class of lazy
// and add the loaded to those images when they're finished loading
// place images in the data-src attribute
<img class="lazy" data-src="1.jpg" />
Defer.dom('img.lazy', 200, 'loaded');

// lazy load containers with the CSS class of container
<div id="container" data-style="background: url(1.jpg)">

// lazy load iframes, pictures, videos, audios...
<iframe class="multi-lazy" title="Youtube"
  width="400" height="300" allowfullscreen
  data-style="background: url( 50% 50% / cover no-repeat;"
<picture class="multi-lazy">
  <source media="(min-width:800px)" data-srcset="large.jpg">
  <source media="(min-width:600px)" data-srcset="medium.jpg">
  <img data-src="small.jpg" alt="Photo" style="width:auto;">
<audio class="multi-lazy" controls>
  <source data-src="1.ogg" type="audio/ogg">
  <source data-src="1.mp3" type="audio/mpeg">
  Your browser does not support the audio tag.
<video class="multi-lazy" width="320" height="240" controls>
  <source data-src="m1.mp4" type="video/mp4">
  <source data-src="1.ogg" type="video/ogg">
  Your browser does not support the video tag.

Author: shinsenter

License: MIT

Official Page: GitHub

Demo: Link

Download: Link

Fancy you stumbling on my piece of the internet. Bonjour!

My name is Anmol and I'm the Blogger-In-Chief of this joint & working as the Chief Technology Officer at Azoora, Inc. I'm putting up my views here trying to help creative solopreneurs, developers & designers build their business using the power of websites, apps & social media, this, is, my jam.

If you're looking to start your own online business with a professional high quality website or mobile app, just get in touch. I'd be more than happy to assist.


Leave a Comment

Your email address will not be published. Required fields are marked *