easy-perf
v1.1.1
Published
Easy performance improvements
Downloads
5
Maintainers
Readme
easy-perf
npm install easy-perf
- defer CSS with
deferCSS
- defer fonts with
deferFonts
- inline SVGs with
inlineSVG
- lazyloading with
lazyload
Use dist/easy-perf.js
for all features bound to window.easyPerf
, or import
the modules you need from src
.
deferCSS
All stylesheets that are not used above-the-fold should have their loading deferred.
The function takes an array of stylesheet URLs, and appends them to <head>
after DOMContentLoaded
.
easyPerf.deferCSS([
'styles-1.css',
'styles-2.css'
]);
deferFonts
Webfonts are not necessary for the user to start consuming content on a page.
Takes an array of font names as they appear in their @font-face
definition, and a class name that is added to <body>
after the fonts are loaded.
easyPerf.deferFonts(['Open Sans'], 'fonts-loaded');
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
.fonts-loaded {
font-family: "Open Sans", sans-serif;
}
inlineSVG
SVG used in <img>
is cached, but can't inherit color with currentColor
. Inlined SVGs, on the other hand, inherit color but are not cached.
This function finds all elements with data-svg-src
, downloads the file with Fetch API and inlines inside that element. Fetched files are cached.
<span data-svg-src="vector.svg"></span>
easyPerf.inlineSVG();
lazyload
All images that appear below-the-fold shouldn't be loaded before the user scrolls down enough to see them.
Those images should have data-src
instead of src
to prevent them from downloading, and data-lazyload="img"
for the function to identify them.
lazyloaded
class is applied after the image is scrolled to.
<img data-src="image.jpg" data-lazyload="img">
easyPerf.lazyload();
Add a fade in transition to make the loading feel more smooth.
<img class="lazyload" data-src="image.jpg" data-lazyload="img">
.lazyload {
opacity: 0;
transition: opacity .2s;
}
.lazyloaded {
opacity: 1;
}
Make sure the image has a set aspect ratio using the padding-bottom trick to prevent content below the image from moving down and causing a reflow.
<div class="aspect-ratio">
<img data-src="image.jpg" data-lazyload="img">
</div>
.aspect-ratio {
position: relative;
padding-top: calc((9 / 16) * 100%);
}
.aspect-ratio img {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
Icon used in test/index.html
by Icomoon https://icomoon.io