Asynchronous loader for script tags when dynamic loading is required
This is a single-file library so simply insert it into your HTML file will be just enough.
<script src="https://cdn.jsdelivr.net/gh/CSharperMantle/async-script-loader@main/src/index.min.js"></script>
window.AsyncScriptLoader = {
loadScript: function(url, baseElem, resolveWhen, isWithIntegrity, integrity, crossorigin) { return new Promise(...); }
}
url
- Astring
of the URL of the script to loadbaseElem
- AnElement
object to insert the script as its child, after its starting tagresolveWhen
- Afunction
to indicate a script is fully executedisWithIntegrity
- Aboolean
to indicate whetherintegrity
andcrossorigin
should be insertedintegrity
- Astring
which stores theintegrity
attribute value of the script element, the same as the one defined in HTML5 Speccrossorigin
- Astring
which stores thecrossorigin
attribute value of the script element- Returns: A
Promise
which will be fulfilled when the script finishes execution and rejected when it fails to load
A live example may be found here, while its JS source code is available here. The core part of the code is listed below.
AsyncScriptLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js', body, () => { return (typeof $ !== 'undefined'); },
true, 'sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==', 'anonymous')
.then(() => {
return AsyncScriptLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/gsap/3.5.1/gsap.min.js', body, () => { return (typeof gsap !== 'undefined'); },
false, null, null)
})
.then(() => {
return AsyncScriptLoader.loadScript('https://cdn.jsdelivr.net/gh/CSharperMantle/CSharperMantle.github.io@HEAD/assets/js/CustomEase-3.5.1.min.js', body, () => { return (typeof CustomEase !== 'undefined'); },
false, null, null)
})
.then(() => {
return AsyncScriptLoader.loadScript('https://cdn.jsdelivr.net/gh/CSharperMantle/CSharperMantle.github.io@HEAD/assets/js/CustomWiggle-3.4.3.min.js', body, () => { return (typeof CustomWiggle !== 'undefined'); },
false, null, null);
})
.then(() => {
loadDropper()
})
.catch((reason) => {
console.log(reason)
})