jQuery具有$.getScript()
函數,您可以使用該函數來檢索外部資產並在全局範圍內評估它們。您可以使用此AJAX功能的回調函數在資產加載後執行工作。
如果您想要加載多個資產,您可以將從jQuery AJAX函數返回的XHR對象推送到一個數組,然後等待數組中的所有XHR對象解析。
單
//get remote asset when a specified page is initialized by jQuery Mobile
$(document).delegate('#my-map-page', 'pageinit', function() {
$.getScript('http://maps.google.com/maps/api/js?sensor=false', function() {
//the code has now been evaluated and you can utilize it here
});
});
多
$(document).delegate('#my-map-page', 'pageinit', function() {
//setup array for XHR objects and one for the URLs of the assets you want to get
var jqXHRs = [],
scripts = ['http://maps.google.com/maps/api/js?sensor=false', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'];
//loop through the script URLs and create an AJAX request to get them,
//also add the XHR object for the request to an array
for (var i = 0, len = scripts.length; i < len; i++) {
jqXHR.push($.getScript(scripts[i]));
}
//use the array of XHR objects we created to wait for all assets to load
$.when(jqXHR).then(function() {
//all the scripts have loaded and are evaluated, do work
});
});
一些文檔:
愛與單項和多項的例子。太棒了! – Lucas 2012-04-10 00:37:50