我认为这是一种常见的情况,很惊讶没有在这里找到答案。就这样吧……
我的 jquerymobile 站点中的某些页面使用外部 javascript。我不希望这些脚本加载到站点的每个页面上。它是移动的,应该可以快速加载。
如何加载外部 javascript,以便在需要引用时在 DOM 中可用。我发现这篇 Stack 文章似乎有很好的技术:Using Javascript to load other external Javascripts
如果我动态加载这个外部 javascript,我应该使用 pageinit 事件吗? http://jquerymobile.com/test/docs/api/events.html
如果我使用这个事件,脚本会在页面正文引用它时加载到 DOM 中……还是会出现对象引用错误?
最佳答案
jQuery 具有 $.getScript()
函数,您可以使用它来检索外部 Assets 并在全局范围内评估它们。您可以利用此 AJAX 函数的回调函数在 Assets 加载后执行工作。
如果您想加载多个 Assets ,您可以将从 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
});
});
一些文档:
$.when()
: http://api.jquery.com/jquery.when$.then()
: http://api.jquery.com/jquery.then$.getScript()
:http://api.jquery.com/jquery.getScriptpageInit
: http://jquerymobile.com/demos/1.1.0-rc.2/docs/api/events.html
关于javascript - jQueryMobile : How to load external Javascripts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10081107/