这对于使用包含仅在所有脚本都已加载时才要运行的代码的回调函数加载多个脚本非常有用。 要加载多个脚本,您需要增强AJAX $ .getScript()函数以处理多个脚本,然后只需将它们添加到第一个参数的数组中,并将回调函数作为第二个参数。
单个jQuery Get脚本
$.getScript('script1.js', function(data, textStatus) {
//do something after script has loaded
});
多个jQuery Get脚本
/* enhance $.getSctipt to handle mutiple scripts */ var getScript = jQuery.getScript; jQuery.getScript = function( resources, callback ) { var // reference declaration & localization length = resources.length, handler = function() { counter++; }, deferreds = [], counter = 0, idx = 0; for ( ; idx < length; idx++ ) { deferreds.push( getScript( resources[ idx ], handler ) ); } jQuery.when.apply( null, deferreds ).then(function() { callback && callback(); }); }; $.getScript(['script1.js','script2.js','script3.js'], function() { //do something after all scripts have loaded }); //or seperate into an array to include var scripts = ['script1.js','script2.js','script3.js']; $.getScript(scripts, function(data, textStatus) { //do something after all scripts have loaded }); [/js]
Any way I discovered: You could just do it this way, say you had to load 3 scripts and the third has a callback. [js] $.get("js/ext/flowplayer-3.2.8.min.js") .pipe($.get("js/eviflowplayer.js")) .pipe($.get("js/evi.flowplayer.js", {}, function() { W.EVI.FLOWPLAYER.init(elem.attr('id')); });