jQuery Mobile 页面加载显示加载器及 document.ready 与 window.onload 执行顺序解析
本文解析 jQuery Mobile 页面加载时显示加载器的实现方法,重点对比 document.ready 与 window.onload 的执行顺序。通过示例说明需延迟调用 showLoader 以避免 JS 未加载完毕,并指导如何根据实际需求在相应事件回调中关闭加载器,解决网速快时加载器显示不明显的问题。
jQuery Mobile 加载器实现与执行顺序分析
要实现此功能,首先需要理清页面加载流程与事件触发的先后次序。参考以下基础示例:
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>验证加载顺序</title>
<script src="../Scripts/jquery-1.7.1.js"></script>
<link href="../Scripts/Mobile/jquery.mobile-1.4.0.min.css" rel="stylesheet" />
<script src="../Scripts/Mobile/jquery.mobile-1.4.0.min.js"></script>
<script>
alert("DOM还没加载");
window.onload = function () {
alert('onload,图片加载完');
}
$(document).ready(function () {
alert('ready,dom加载完');
})
</script>
</head>
<body >
<form id="form1" runat="server">
<img src="http://images.aviary.com/imagesv5/feather_default.jpg" />
<img src="http://car0.autoimg.cn/car/upload/2015/1/8/v_20150108092921264345010.jpg" />
</form>
</body>
</html>
运行结果显示执行顺序为第 9 行、第 14 行、第 11 行。即便调整第 9 行代码在脚本中的位置,最终执行结果保持一致。明确这一时序后,若需在页面数据请求、图片等多媒体资源加载期间展示 jQuery Mobile 的加载指示器,并在全部加载完成后将其关闭,可参考如下实现方案:
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>验证加载顺序</title>
<script src="../Scripts/jquery-1.7.1.js"></script>
<link href="../Scripts/Mobile/jquery.mobile-1.4.0.min.css" rel="stylesheet" />
<script src="../Scripts/Mobile/jquery.mobile-1.4.0.min.js"></script>
<script>
setTimeout('showLoader()', 100);//这里要延迟一下,直接调用无法显示加载器
//显示加载器.for jQuery Mobile 1.2.0
function showLoader() {
$.mobile.loading('show', {
text: '正在登陆...', //加载器中显示的文字
textVisible: true, //是否显示文字
theme: 'a', //加载器主题样式a-e
textonly: false, //是否只显示文字
html: "" //要显示的html内容,如图片等
});
}
//隐藏加载器.for jQuery Mobile 1.2.0
function hideLoader() {
$.mobile.loading('hide');
}
window.onload = function () {
hideLoader();
//setTimeout('hideLoader()', 5000);//延迟5秒,模拟图片和多媒体加载耗时
}
$(document).ready(function () {
//setTimeout('hideLoader()', 5000);//延迟5秒,模拟页面请求数据耗时,ajax异步请求等放在这里
})
</script>
</head>
<body >
<form id="form1" runat="server">
<img src="http://images.aviary.com/imagesv5/feather_default.jpg" />
<img src="http://car0.autoimg.cn/car/upload/2015/1/8/v_20150108092921264345010.jpg" />
</form>
</body>
</html>
关键说明如下:
1)第 9 行代码需设置适当延迟执行。若直接调用,可能因引用的 JS 文件尚未加载完毕,导致 showLoader 方法无法正确执行,进而无法显示加载器。
2)关闭加载器的逻辑可置于 document.ready 或 window.onload 事件中,具体选择应依据页面的实际执行需求而定。
3)若网络速度极快,图片瞬间加载完成,用户可能无法观察到加载器显示与关闭的明显过程。
以上介绍了 jQuery Mobile 在页面加载时添加加载中效果的方法,并对比了 document.ready 与 window.onload 的执行顺序,希望能对您有所帮助。如有疑问欢迎留言,小编会及时回复。感谢大家对本站的支持!
定制 Quill.js 主题样式:修改默认 CSS 与添加自定义类名
2026-11-04 11:21:35
混淆JS代码怎么在线反混淆并格式化阅读
2026-11-03 21:46:39
JS在线编辑器代码报错怎么调试?控制台使用技巧
2026-11-03 21:24:56
从 marked.js 旧版本升级到最新版:API 变更与迁移指南
2026-11-03 17:38:17
JS富文本编辑器Quill与代码编辑器CodeMirror的区别及应用场景
2026-11-03 16:52:09
