ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

jqueryMobile:如何加载外部Javascripts

2019-06-30 07:22:50  阅读:119  来源: 互联网

标签:javascript jquery-mobile


我认为这是一个常见的情况,并且很惊讶没有在这里找到答案.所以这里……

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

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

如果我动态加载这个外部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

标签:javascript,jquery-mobile
来源: https://codeday.me/bug/20190630/1334221.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有