import lazyLoad from 'lazy-loader';
let mapPromise;
function getMap() {
return mapPromise || (
mapPromise = lazyLoad('/chunks/map.js', () => {
return new GoogleMap({
markers: [ /* ... */ ]
});
}, true)
);
}
getMap().then(map => {
// boot up your map stuff
});
Created
August 23, 2019 16:30
-
-
Save developit/581c772404b834096dbbb593476454ca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const rick = typeof requestIdleCallback === 'function' ? requestIdleCallback : (fn => setTimeout(fn, 1000)); | |
export default function lazyLoad(src, boot, asModule = true) { | |
return new Promise((resolve, reject) => { | |
const link = document.createElement('link'); | |
const head = document.head; | |
link.rel = asModule && link.relList && link.relList.supports && link.relList.supports('modulepreload') ? 'modulepreload' : 'preload'; | |
if (asModule) link.crossOrigin = true; | |
link.href = src; | |
link.onerror = reject; | |
link.onload = () => { | |
rick(() => { | |
const script = document.createElement('script'); | |
if (asModule) script.crossOrigin = script.type = 'module'; | |
script.async = true; | |
script.src = link.href; | |
head.insertBefore(script, link); | |
if (boot) { | |
rick(() => { | |
resolve(boot()); | |
}); | |
} | |
else { | |
resolve(); | |
}); | |
}; | |
head.appendChild(link); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "@developit/lazy-loader", | |
"version": "0.1.0", | |
"module": "lazy-loader.js" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment