javascript - jQueryMobile : How to load external Javascripts

标签 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 中……还是会出现对象引用错误?

最佳答案

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

一些文档:

关于javascript - jQueryMobile : How to load external Javascripts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10081107/

相关文章:

javascript - 如何在不害怕的情况下更新 JavaScript 库?

javascript - Angular 2/Typescript - 类型错误 : ClassName is not a constructor

javascript - 如何使用 javascript 将单词放在单个冒号中并用逗号分隔单词

android - 全屏背景图片不随内容滚动 html5 phonegap

jquery - 如何附加嵌套的ul

javascript - es6在类中导入类

javascript - 在 vue/vite 项目中将文件作为字符串加载

jquery - 我需要在 DIV 中插入 append jquery 的结果,只是 css 不能正常工作

jquery - 异步加载 jQuery Mobile 脚本?

css - MVC 4 移动样式在脚本更新后停止工作