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();
})
});
您可以使用document.createElement
将脚本动态添加到页面中,然后使用.async = true
将其添加到DOM中,并从脚本的init()
事件监听器中调用游戏的load
函数:
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作为参数并为Promise
事件侦听器返回load
来使其更加通用,因此使用此功能的页面可以具有自己的自定义加载逻辑:
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()
函数的工作方式,顺便说一句。