【问题标题】:Modernizr.load Deprecated. Yepnope.js Deprecated. Current Alternatives?Modernizr.load 已弃用。 Yepnope.js 已弃用。当前的替代方案?
【发布时间】:2020-04-28 01:13:56
【问题描述】:

Modernizr.load 和 yepnope.js 都已被弃用。 我们现在如何有条件地调用 javascript 文件? 可以举个例子吗?

这是我要加载的 javascript

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);

还有modernizr的代码:

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

【问题讨论】:

    标签: deprecated modernizr yepnope


    【解决方案1】:

    您可以使用document.createElement 将脚本动态添加到页面,并使用.async = true 将其添加到DOM,并从脚本的load 事件监听器调用您游戏的init() 函数:

    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 );
    }
    

    您可以通过将脚本的 URL 作为参数传递并为 load 事件侦听器返回 Promise 来使其更通用,因此使用此函数的页面可以有自己的自定义加载逻辑:

    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 );
        } );
    }
    

    这样使用:

    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." ); // 
            }
        }
    
    }
    

    ...这就是 require() 按需加载模块的工作原理,顺便说一句。

    【讨论】:

      猜你喜欢
      • 2016-03-03
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 2020-11-07
      • 2020-05-22
      • 2022-11-09
      • 1970-01-01
      相关资源
      最近更新 更多