如何在jquery-mobile / phonegap的$(document).ready()/ onDeviceReady()上加载脚本
我正在使用PhoneGap和jQuery Mobile开发应用程序。
现在当页面加载时,我想加载一个script(.js file)
。 基本上是onDeviceReady
或$(document).ready()
。 怎么做?
//wait for document.ready to fire $(function () { //then load the JavaScript file $.getScript('script.js'); });
http://api.jquery.com/jquery.getscript
//create a callback function function myCallback () { //create a script element and set it's type and async attributes var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; //set the source of the script element script.src = 'script.js'; //add the script element to the DOM var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(script, s); } //add event listener for the deviceready function to run our callback function document.addEventListener("deviceready", myCallback, false);
http://docs.phonegap.com/en/1.4.1/phonegap_events_events.md.html#deviceready
第二个代码段是Google Analytic代码的略微修改版本,用于异步地向DOM添加脚本。
UPDATE
您还可以将标记的
defer
属性设置为true
并且在DOM准备好之后才会执行。 请参阅此处的一些文档: https : //developer.mozilla.org/en-US/docs/HTML/Element/Script
- 无法从第二个包含的js文件中的第一个包含的javascript文件调用函数
- JQuery Mobile 1.3.1“$ .mobile.loading”无效
- 使用jquery mobile中的点击替换所有点击事件以加快速度
- 如何在Phonegap和JQM中使用FastClick.js?
- 在真实设备上的cordova app请求中出现net :: ERR_CONNECTION_TIMED_OUT错误
- Phonegap – 在启用自动定位的同时防止旋转?
- Phonegap SQLite错误23未授权
- 由jquery mobile在电话差距中实现方向改变事件
- 用于WP8(Lumia 920)设备的jQuery / HTML5 / gwt应用程序:垂直css滚动修复