Skip to content

Instantly share code, notes, and snippets.

@Kalki5
Created March 13, 2020 11:16
Show Gist options
  • Save Kalki5/33465f7426368299e523a16c8dfc4e8a to your computer and use it in GitHub Desktop.
Save Kalki5/33465f7426368299e523a16c8dfc4e8a to your computer and use it in GitHub Desktop.
Lazy Loading CSS and JS libraries
<!-- Preloading Files -->
<script>
function lazyLoadLibraries() {
const csslibraries = [
'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/monokai-sublime.min.css',
]
const jslibraries = [
'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/highlight.min.js',
]
const cssLinkTags = []
for (const library of csslibraries) {
let link = document.createElement('link'); link.href = library; link.rel = 'preload'; link.crossorigin = ''; link.as = 'style';
document.head.appendChild(link);
cssLinkTags.push(link);
}
for (const library of jslibraries) {
let link = document.createElement('link'); link.href = library; link.rel = 'preload'; link.crossorigin = ''; link.as = 'script';
document.head.appendChild(link);
}
setTimeout(() => {
for (const cssLinkTag of cssLinkTags) { cssLinkTag.rel = 'stylesheet';}
for (const library of jslibraries) {
let preloadedScript = document.createElement('script');
preloadedScript.src = library;
document.head.prepend(preloadedScript);
}
}, 0);
}
window.addEventListener('load', lazyLoadLibraries);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment