You can dynamically add scripts to a page with document.createElement
and adding it to the DOM with .async = true
and call your game's init()
function from the script's load
event-listener:
function addGameScriptToPage() {
const scriptElement = document.createElement('script');
scriptElement.async = true;
scriptElement.addEventListener( 'load', function( e ) { new BubbleShoot.Game().init(); } );
scriptElement.src = '__js/game.js';
document.head.appendChild( scriptElement );
}
You can make it more generic by passing the script's URL as a parameter and returning a Promise
for the load
event-listener, so pages using this function can have their own custom load logic:
function addScriptToPage( scriptUrl ) {
return new Promise( ( resolve, reject ) => {
const scriptElement = document.createElement('script');
scriptElement.async = true;
scriptElement.addEventListener( 'load', function( e ) {
resolve( e );
);
scriptElement.addEventListener( 'error', function( e ) {
reject( e );
);
scriptElement.src = scriptUrl;
document.head.appendChild( scriptElement );
} );
}
Used like so:
async function doStuff() {
const shouldLoadGame = prompt( "Would you like to play a game of global thermonuclear war?" );
if( shouldLoadGame ) {
try {
await addScriptToPage( "__js/game.js" );
// This code runs when the 'load' event listener calls `resolve(e)`.
const g = new BubbleShoot.Game();
g.init();
}
catch( err ) {
// This code runs when the 'error' event listener calls `reject(e)`.
alert( "Game failed to load." ); //
}
}
}
...and this is pretty much how the require()
function for loading modules on-demand works, btw.