shinsenter / Defer.js
Programming Languages
Projects that are alternatives of or similar to Defer.js
Package @shinsenter/defer.js
๐ฅ A super small, super efficient library that helps you lazy load almost everything like images, video, audio, iframes as well as stylesheets, and JavaScript.
- Package: @shinsenter/defer.js
- Version: 2.0
- Author: Mai Nhut Tan [email protected]
- Copyright: 2021 AppSeeds https://code.shin.company/
- License: MIT
Use cases
In real life, many resources and third-party scripts, such as jQuery, are used to enhance our website to add additional interactivity, animations, and other effects.
Unfortunately, third-party scripts usually block page rendering and further downloading resources of the page.
There is a common knowledge
that you should use <script src=".." async>
(or <script src=".." defer>
)
and/or put your scripts at the very bottom of the page,
so that as much as possible of the page gets loaded
and rendered to the user, as fast as possible.
But in various cases, using async
or defer
attributes
does not deliver faster page speed than defer.js does.
Furthermore defer.js also gives you very simple ways
to flexibly optimize other resources in your website.
Good points
- ๐งถ Under 1KB (mingzipped size)
- ๐ฏ No dependencies, no jQuery
- โก๏ธ Native API, blazing fast
- โ Supports legacy browsers (IE9+)
- ๐งฉ Lazy loading for almost everything
- ๐ Very easy to use
- ๐ค Works well with your favorite frameworks
Browser support
Available in latest browsers,
also works perfectly with Internet Explorer 9
* (with IntersectionObserver
polyfill library) and later.
- ๐ฅ IE9+ / Microsoft EDGE *
- ๐ฅ Firefox 4+
- ๐ฅ Safari 3+
- ๐ฅ Chrome *
- ๐ฅ Opera *
- ๐ฑ Android 4+
- ๐ฑ iOS 3.2+
Getting started
Basic
Add defer.min.js
from this library into your HTML page,
just below the opening <head>
tag.
You may download a ZIP of this library, or load it from a CND like below example.
<head>
<meta charset="UTF-8" />
<title>My Awesome Page</title>
<!-- Put defer.min.js here -->
<script src="https://cdn.jsdelivr.net/npm/@shinsenter/[email protected]/dist/defer.min.js"></script>
<!-- To support older browsers such as Internet Explorer 9 -->
<!-- You may want to put IntersectionObserver polyfill right after defer.min.js tag -->
<script>'IntersectionObserver'in window||document.write('<script src="https://polyfill.io/v3/polyfill.min.js?features=IntersectionObserver"><\/script>');</script>
<!-- ... -->
</head>
Compatibility with previous releases
I strongly recommend that you should migrate to the latest version for better performance.
If you have no time and want to ensure compatibility
with older version, use defer_plus.min.js
instead of defer.min.js
.
<!-- Put defer_plus.min.js here -->
<script src="https://cdn.jsdelivr.net/npm/@shinsenter/[email protected]/dist/defer_plus.min.js"></script>
<!-- To support older browsers such as Internet Explorer 9 -->
<!-- You may want to put IntersectionObserver polyfill right after defer.min.js tag -->
<script>'IntersectionObserver'in window||document.write('<script src="https://polyfill.io/v3/polyfill.min.js?features=IntersectionObserver"><\/script>');</script>
Inlining the library
Since size of defer.js library is optimized
to minimum size, you can inline entire library
in the <head>
of the HTML document
to minimize the number of requests.
<head>
<meta charset="UTF-8" />
<title>My Awesome Page</title>
<!-- Inlining defer.min.js -->
<script>/* content of defer.min.js will be here */</script>
<!-- ... -->
</head>
Functions
-
Defer(func, [delay]) โ
void
-
.all([selector]) โ
void
-
.js(src, [id], [delay], [callback]) โ
void
-
.css(src, [id], [delay], [callback]) โ
void
-
.dom([selector], [delay], [cssclass], [validate], [observeOptions]) โ
void
-
.reveal(element) โ
void
-
.all([selector]) โ
defer(func, [delay])deferscript(src, [id], [delay], [callback])deferstyle(src, [id], [delay], [callback])deferimg([selector], [delay], [cssclass], [validate], [observeOptions])
Typedefs
void
Defer(func, [delay]) โ Used to delay execution of JavaScript which may adversely affect the loading of your web page.
All JavaScript delayed by Defer()
will only executed
after the web page has completely loaded.
Kind: global function Access: public Since: 2.0
Param | Type | Default | Description |
---|---|---|---|
func | function |
The function that will be deferred. | |
[delay] | number |
0 |
The duration in miliseconds to delay the func function. |
Example Delay some heavy DOM manipulations in JavaScript.
Defer(function() {
// Some JavaScript that may block page rendering
// such as calling jQuery's fadeIn() feature
jQuery('div').hide().fadeIn().show();
}); // <- script runs after the page has completely loaded
Example Delay the same JavaScript as above for 3000ms.
Defer(function() {
jQuery('div').hide().fadeIn().show();
}, 3000); // <- Added 3000 = Delay for 3000ms
-
Defer(func, [delay]) โ
void
-
.all([selector]) โ
void
-
.js(src, [id], [delay], [callback]) โ
void
-
.css(src, [id], [delay], [callback]) โ
void
-
.dom([selector], [delay], [cssclass], [validate], [observeOptions]) โ
void
-
.reveal(element) โ
void
-
.all([selector]) โ
void
Defer.all([selector]) โ By default, this function is triggered automatically.
All script tags with attribute <script type="deferjs">
will be delayed and automatically executed
as soon as the page has completely loaded.
This function is useful when you don't want heavy JavaScript works to affect your website loading speed.
Kind: static method of Defer
Access: public
Since: 2.0
Param | Type | Default | Description |
---|---|---|---|
[selector] | string |
"[type=deferjs]" |
A CSS selector that queries script tags will be deferred. |
Example
You just need to simply change type="text/javascript"
to type="deferjs"
,
or add type="deferjs"
to your script tag for it to take effect.
Before:
<script type="text/javascript" src="heavy-library.js"></script>
<script>// heavy script here </script>
After:
<script type="deferjs" src="heavy-library.js"></script>
<script type="deferjs">// heavy script here </script>
Example
If you don't want the <script type="deferjs">
syntax,
or you want to define another name for website,
please call Defer.all()
manually at the bottom of the <body>
tag.
This example uses type="myjs"
instead of type="deferjs"
:
<script type="myjs" src="heavy-library.js"></script>
<script type="myjs">// heavy script here </script>
<!-- Call Defer.all() at the bottom of the `<body>` tag -->
<script>Defer.all('script[type="myjs"]');</script>
void
Defer.js(src, [id], [delay], [callback]) โ For lazy loading external JavaScript files.
This function is useful when you don't want heavy JavaScript (especially the widgets of social networks, ad services) to affect your website loading speed.
Kind: static method of Defer
Access: public
Since: 2.0
Param | Type | Default | Description |
---|---|---|---|
src | string |
URL to the js file that should be lazy loaded. | |
[id] | string |
The ID will be assigned to the script tag to avoid downloading the same file multiple times. | |
[delay] | number |
0 |
The duration in miliseconds to delay loading the js file. |
[callback] | closure |
The callback function will be executed if the js file is successfully loaded. |
Example Delay loading of Facebook SDK after 3000ms.
Defer.js('https://connect.facebook.net/en_US/sdk.js', 'fb-sdk', 3000);
Example Delay loading of AddThis SDK after 5000ms.
var addthis_id = 'ra-5c68e61cf456f1cb';
Defer.js('https://s7.addthis.com/js/300/addthis_widget.js#pubid=' + addthis_id, 'addthis-js', 5000);
void
Defer.css(src, [id], [delay], [callback]) โ For lazy loading external CSS files.
This function is useful when you don't want heavy CSS (like Web Fonts) to affect your website loading speed.
Kind: static method of Defer
Access: public
Since: 2.0
Param | Type | Default | Description |
---|---|---|---|
src | string |
URL to the css file that should be lazy loaded. | |
[id] | string |
The ID will be assigned to the script tag to avoid downloading the same file multiple times. | |
[delay] | number |
0 |
The duration in miliseconds to delay loading the css file. |
[callback] | closure |
The callback function will be executed if the css file is successfully loaded. |
Example Lazy load FontAwesome Webfont from its CDN.
Defer.css('https://pro.fontawesome.com/releases/v5.10.0/css/all.css', 'fa5-css');
Example Delay loading animate.css from CDN for 1000ms.
Defer.css('https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css', 'animate-css', 1000);
void
Defer.dom([selector], [delay], [cssclass], [validate], [observeOptions]) โ For lazy loading attributes of any element on the page.
Basically, the Defer.dom
function converts all data-*
attributes
into regular attributes (e.g. from data-src
to src
)
when user scrolling to the position
where the element appears within the browser's viewport.
Most of modern browsers support IntersectionObserver feature.
To take advantage of native performance
for older browsers that doesn't support this feature (such as IE9),
you should load IntersectionObserver
polyfill library
right after the defer.min.js
script tag as following example:
<!-- Put defer.min.js here -->
<script src="https://cdn.jsdelivr.net/npm/@shinsenter/[email protected]/dist/defer.min.js"></script>
<!-- Put polyfill right after defer.min.js tag -->
<script>'IntersectionObserver'in window||document.write('<script src="https://polyfill.io/v3/polyfill.min.js?features=IntersectionObserver"><\/script>');</script>
Kind: static method of Defer
Access: public
Since: 2.0
Param | Type | Default | Description |
---|---|---|---|
[selector] | string |
"[data-src]" |
A CSS selector that queries elements will be lazy loaded. |
[delay] | number |
0 |
The duration in miliseconds to delay the lazy loading for the elements. |
[cssclass] | string |
A CSS class will be added automatically after when an element has been loaded successfully. | |
[validate] | closure |
A function will be executed with element will be lazy loaded as its argument. If the function returns false , lazy loading for that element will be skipped. |
|
[observeOptions] | object |
Intersection observer options |
Example
Basic usage:
Lazy load all <img>
tags which have CSS class lazy
.
<script>Defer.dom('img.lazy');</script>
<!-- Here may be a very long content -->
<img class="lazy" alt="Photo 1" data-src="https://picsum.photos/200/300?random=1" width="200" height="300" />
<img class="lazy" alt="Photo 2" data-src="https://picsum.photos/200/300?random=2" width="200" height="300" />
<img class="lazy" alt="Photo 3" data-src="https://picsum.photos/200/300?random=3" width="200" height="300" />
Example
Basic usage:
Lazy load background image of a div
tag.
<style>
#my_div {
width: 300;
height: 200;
}
</style>
<script>
// Lazy load div tag which has `id="my_div"`
Defer.dom('#my_div');
</script>
<!-- Here may be a very long content -->
<div id="my_div"
data-style="background: url(https://img.youtube.com/vi/Uz970DggW7E/hqdefault.jpg) 50% 50% / cover no-repeat;">
<!-- The content -->
</div>
Example
Advanced usage:
Delay lazy loading <img>
tags 200ms after the page has completely loaded.
Then it will add a CSS class loaded
to the fully lazy loaded image element.
<script>Defer.dom('img.lazy-extra', 200, 'loaded');</script>
<!-- Here may be a very long content -->
<img class="lazy-extra" alt="Photo 1" data-src="https://picsum.photos/200/300?random=4" width="200" height="300" />
<img class="lazy-extra" alt="Photo 2" data-src="https://picsum.photos/200/300?random=5" width="200" height="300" />
<img class="lazy-extra" alt="Photo 3" data-src="https://picsum.photos/200/300?random=6" width="200" height="300" />
Example Advanced usage: Lazy load with Intersection observer options
<script>
// Preload images within 200% of the current viewport size.
Defer.dom("img.lazy-sooner", 200, "loaded", null, {
rootMargin: "200%"
});
</script>
<!-- Here may be a very long content -->
<img class="lazy-sooner" alt="Photo 1" data-src="https://picsum.photos/200/300?random=7" width="200" height="300" />
<img class="lazy-sooner" alt="Photo 2" data-src="https://picsum.photos/200/300?random=8" width="200" height="300" />
<img class="lazy-sooner" alt="Photo 3" data-src="https://picsum.photos/200/300?random=9" width="200" height="300" />
Example We can use CSS class that added to the lazy loaded element to add animation to the successfully loaded elements.
<script>Defer.dom('img.fade', 200, 'loaded');</script>
<style>
img.fade {
transition: opacity 500ms ease-in-out;
opacity: 0;
}
img.fade.loaded {
background: none;
opacity: 1;
}
</style>
<!-- Here may be a very long content -->
<img class="fade" alt="Photo 1" data-src="https://picsum.photos/200/300?random=10" width="200" height="300" />
<img class="fade" alt="Photo 2" data-src="https://picsum.photos/200/300?random=11" width="200" height="300" />
<img class="fade" alt="Photo 3" data-src="https://picsum.photos/200/300?random=12" width="200" height="300" />
Example
This function can be used similarly for other tags
such as <iframe>
, <video>
, <audio>
, <picture>
tags.
<script>
// Lazy load all elements which have CSS class `multi-lazy`
Defer.dom('.multi-lazy', 200, 'loaded');
</script>
<!-- Here may be a very long content -->
<iframe class="multi-lazy" title="Youtube"
width="400" height="300" allowfullscreen
allow="accelerometer;autoplay;encrypted-media;gyroscope;picture-in-picture"
data-style="background: url(https://img.youtube.com/vi/Uz970DggW7E/hqdefault.jpg) 50% 50% / cover no-repeat;"
data-src="https://www.youtube.com/embed/Uz970DggW7E"></iframe>
<picture class="multi-lazy">
<source media="(min-width:800px)" data-srcset="https://picsum.photos/800/1200">
<source media="(min-width:600px)" data-srcset="https://picsum.photos/600/900">
<img data-src="https://picsum.photos/200/300" alt="Photo" style="width:auto;">
</picture>
<audio class="multi-lazy" controls>
<source data-src="sound.ogg" type="audio/ogg">
<source data-src="sound.mp3" type="audio/mpeg">
Your browser does not support the audio tag.
</audio>
<video class="multi-lazy" width="320" height="240" controls>
<source data-src="movie.mp4" type="video/mp4">
<source data-src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
Example
Or even execute a piece of JavaScript
when the user scrolls to the element #scroll_reveal
.
<script>
// Show an alert when user scrolled to #scroll_reveal
Defer.dom('#scroll_reveal', null, null, function(element) {
window.alert('You scrolled to #' + element.id);
});
</script>
<!-- Here may be a very long content -->
<div id="scroll_reveal">
This is my content.
</div>
Example
Combine with other Defer functions.
Delay loading highlightjs library for 1000ms.
Then when you scroll to any code
tag, enable code highlighting for it.
var base = 'https://cdn.jsdelivr.net/npm/[email protected]';
Defer.css(base + '/styles/rainbow.css', 'hljs-css', 1000);
Defer.js(base + '/highlight.pack.min.js', 'hljs-js', 1000, function () {
Defer.dom('pre code', 0, 'ide-loaded', function (block) {
hljs.highlightBlock(block);
});
});
void
Defer.reveal(element) โ Reveal an element which is lazyloaded by the library
Kind: static method of Defer
Access: public
Since: 2.1
Param | Type | Description |
---|---|---|
element | Node |
The DOM Node element |
Example
// Show single element
var node = document.getElementById('my-video');
Defer.reveal(node);
// Show multiple elements
document.querySelectorAll('.multi-lazy').forEach(function(node) {
Defer.reveal(node);
});
defer(func, [delay])
Deprecated
Kind: global function Access: public See: Defer Since: 1.0
Param | Type |
---|---|
func | function |
[delay] | number |
deferscript(src, [id], [delay], [callback])
Deprecated
Kind: global function Access: public See: js Since: 1.0
Param | Type |
---|---|
src | string |
[id] | string |
[delay] | number |
[callback] | callback |
deferstyle(src, [id], [delay], [callback])
Deprecated
Kind: global function Access: public See: css Since: 1.0
Param | Type |
---|---|
src | string |
[id] | string |
[delay] | number |
[callback] | callback |
deferimg([selector], [delay], [cssclass], [validate], [observeOptions])
Deprecated
Kind: global function Access: public See: dom Since: 1.0
Param | Type |
---|---|
[selector] | string |
[delay] | number |
[cssclass] | string |
[validate] | callback |
[observeOptions] | object |
void
function โ A definition for an ordinary function, used as a parameter to another function.
Kind: global typedef
void
| bool
closure โ The definition for a function that takes one parameter is a DOM Node element
Kind: global typedef
Param | Type | Description |
---|---|---|
element | Node |
The DOM Node element |
Node
The DOM Node interface
Kind: global typedef See: https://developer.mozilla.org/en-US/docs/Web/API/Node
Defer.js for another platforms
PHP library
https://github.com/shinsenter/defer.php/
๐ A PHP library that focuses on minimizing payload size of HTML document and optimizing processing on the browser when rendering the web page.
Wordpress plugin
https://github.com/shinsenter/defer-wordpress/
โก๏ธ A native, blazing fast lazy loader. โ Legacy browsers support (IE9+). ๐ฏ SEO friendly. ๐งฉ Lazy load almost anything.
Laravel package
Under development.
Support my activities
From Vietnam ๐ป๐ณ with love.