doitlater
Increase page loading speed, just load/execute unnecessary things later!
Defer scripts, styles, html, json, images, functions!
Use promise-polyfill for old browsers support
Install
npm install doitlater --save
Usage
Execute a snippet (after DOM Ready event for example):
doitlater.waitFor("DOMReady").then(() => {
doitlater.load("gtm", () => {
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXX');
});
});
window.addEventListener('load', () => {
doitlater.add("DOMReady", Promise.resolve);
});
Load a stylesheet:
doitlater.waitFor("gtm").then(() => {
doitlater.load("materializecss", "//cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css");
});
Preaload images:
doitlater.load("header-images", ["/img/logo.png", "/img/bg.jpg"]);
Load JSON:
doitlater.load("headerJSON", "/config/header.json");
Execute functions:
doitlater.waitFor("DOMReady").then(() => {
doitlater.load("logging", () => { console.log("DOM Ready")});
});
doitlater.waitFor("logging").then(() => {
console.log("After logging");
});
Mixed loading:
doitlater.load(
"resources",
[
"/img/logo.png", "/config/header.json", "/css/header.css",
() => { console.log("Logging")}
]
);
Load a view (HTML file)
doitlater.waitFor("DOMReady").then(() => {
doitlater.load("headerHTML", "/view/header.html").then(result => {
const html = result[0];
document.body.insertAdjacentHTML("afterend", html);
})
});
Reuse your promises
doitlater.add(
"headerLoaded",
Promise.all([
doitlater.waitFor("resources"),
doitlater.waitFor("headerHTML")
])
);
doitlater.waitFor("headerLoaded").then(()=>{
console.log("Header has been loaded");
});
async/await example
await doitlater.waitFor("DOMReady");
await doitlater.load("resources", [
"/img/logo.png", "/config/header.json", "/css/header.css"
]);
Other useful methods
createDefer
const defer = doitlater.createDefer();
defer.promise.then(() => { console.log("Resolved")});
defer.resolve();
runLater
doitlater.runLater(() => {
console.log("Executed in Idle or in a new frame if it's supported");
});
For more detailed information read API