jqueryMobile:如何加载外部 Javascript

Luc*_*cas 5 javascript jquery-mobile

我认为这是一个常见的情况,但很惊讶没有在这里找到答案。所以就这样...

我的 jquerymobile 网站中的某些页面正在使用外部 javascript。我不希望这些脚本加载到网站的每个页面上。它是移动的,并且加载速度应该很快。

如何加载外部 javascript,以便在需要引用时可以在 DOM 中使用它。我发现这篇 Stack 文章似乎有一个很好的技术:Using Javascript to load other external Javascripts

如果我动态加载这个外部 javascript,我应该使用 pageinit 事件吗?http://jquerymobile.com/test/docs/api/events.html

如果我使用此事件,当页面主体引用脚本时,脚本是否会加载到 DOM 中...或者我会收到对象引用错误吗?

Jas*_*per 4

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
    });
});
Run Code Online (Sandbox Code Playgroud)

多种的

$(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
    });
});
Run Code Online (Sandbox Code Playgroud)

一些文档: