Javascript 如何在jquery mobile/phonegap的$(document.ready()/ondevicerady()上加载脚本

Javascript 如何在jquery mobile/phonegap的$(document.ready()/ondevicerady()上加载脚本,javascript,jquery,jquery-mobile,cordova,Javascript,Jquery,Jquery Mobile,Cordova,我正在使用PhoneGap和jQuery Mobile开发一个应用程序 现在,当页面被加载时,我想加载一个脚本(.js文件)。基本上是ondevicerady或$(document).ready()。怎么做 //wait for document.ready to fire $(function () { //then load the JavaScript file $.getScript('script.js'); }); 第二个代码段是Google分析代码的一个稍加

我正在使用PhoneGap和jQuery Mobile开发一个应用程序

现在,当页面被加载时,我想加载一个
脚本(.js文件)
。基本上是
ondevicerady
$(document).ready()
。怎么做

//wait for document.ready to fire
$(function () {

    //then load the JavaScript file
    $.getScript('script.js');
});

第二个代码段是Google分析代码的一个稍加修改的版本,用于向DOM异步添加脚本

更新


您还可以将
标记的
defer
属性设置为
true
,直到准备好DOM之后才会执行该属性。请参阅此处的一些文档:

谢谢Jasper。答案是准确的…:DI也遇到了IE8在刷新时中断的问题。使用$(document).ready()调用为我解决了这个问题。谢谢你的回答!注意:getScript是异步的,因此调用在被调用脚本中声明的函数可能会导致“未定义”错误。请参阅:@Costa The
$。getScript
方法还有一个回调参数,您可以使用。@Jasper回调在加载代码时运行,而不是在执行代码时运行,因此不可靠
//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);