jqueryMobile:如何加载外部Javascripts
jqueryMobile: How to load external Javascripts
我认为这是一种常见的情况,很惊讶在这里找不到答案。所以它来了...
我的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
相关文章:
- 使用javascript在Flash中加载外部图像
- 如何在运行时在angular 2中加载外部js脚本
- Chrome扩展无法通过清单加载外部javascript
- 加载Angular视图后加载外部脚本
- Cordova/Phonegap在主要的Cordova网络视图中加载外部站点
- IE 9 BHO插件.加载外部JS文件时出现错误SCRIPT1014
- 是否有用于加载外部脚本的JavaScript库
- 使用纯Javascript加载外部URL内容
- 在Chrome扩展中加载外部javascript
- 在扩展 jQuery 之前加载外部资源
- 无法加载外部 JavaScript 文件 - Codeigniter
- jquery .load() 不加载外部 JS
- GO - html 文件无法加载外部 js 文件
- jQuery 不会使用 .load() 加载外部 html 模板
- 使用HTML5缓存时无法加载外部资源
- 色盒延迟打开;锁定“;当加载外部javascript文件时
- 使用load()加载外部文件,然后使用fancybox插件进行修改并显示
- 在Ember应用程序中加载外部域脚本
- html javascript加载外部脚本
- 如何防止加载外部资源,同时防止“在'文档'上执行'写入'失败”错误