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
});
});
一些文档: