Is it possible to call in a .js
file synchronously and then use it immediately afterward?
This works for modern 'evergreen' browsers that support async/await and fetch.
This example is simplified, without error handling, to show the basic principals at work.
// This is a modern JS dependency fetcher - a "webpack" for the browser
const addDependentScripts = async function( scriptsToAdd ) {
// Create an empty script element
const s=document.createElement('script')
// Fetch each script in turn, waiting until the source has arrived
// before continuing to fetch the next.
for ( var i = 0; i < scriptsToAdd.length; i++ ) {
let r = await fetch( scriptsToAdd[i] )
// Here we append the incoming javascript text to our script element.
s.text += await r.text()
}
// Finally, add our new script element to the page. It's
// during this operation that the new bundle of JS code 'goes live'.
document.querySelector('body').appendChild(s)
}
// call our browser "webpack" bundler
addDependentScripts( [
'https://code.jquery.com/jquery-3.5.1.slim.min.js',
'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js'
] )