1

Modernizr.load and yepnope.js have both been deprecated. How do we conditionally call javascript files now? Could you give me a example?

This is the javascript that I want to load

var BubbleShoot = window.BubbleShoot || {};
BubbleShoot.Game = (function($){
var Game = function(){
    this.init = function(){
      $(".but_satart_game").bind("click", startGame);
    };
    var startGame = function(){
      console.log("dentro de startGame  en game.js");
      //$(".but_satart_game").unbind("click");
      //BubbleShoot.ui.hideDialog();
    };

  };
   return Game;
})(jQuery);

And modernizr's code:

  Modernizr.load({
  load: "_js/game.js",
  complete: function(){
    $(function(){
      var game = new BubbleShoot.Game();
      game.init();
    })
});
Byron2017
  • 871
  • 2
  • 11
  • 23

1 Answers1

1

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.

Dai
  • 141,631
  • 28
  • 261
  • 374