jqueryMobile:如何加载外部Javascripts

jqueryMobile: How to load external Javascripts

本文关键字:加载 外部 Javascripts 何加载 jqueryMobile      更新时间:2023-09-26

我认为这是一种常见的情况,很惊讶在这里找不到答案。所以它来了...

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

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

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

如果我使用此事件,脚本是否会在页面正文引用它时加载到 DOM 中......还是会收到对象引用错误?

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
    });
});

一些文档:

  • $.when() : http://api.jquery.com/jquery.when
  • $.then() : http://api.jquery.com/jquery.then
  • $.getScript() : http://api.jquery.com/jquery.getScript
  • pageInit : http://jquerymobile.com/demos/1.1.0-rc.2/docs/api/events.html