如何在jquery mobile/phonegap的$(document).ready()/onDeviceReady(

How to load a script on $(document).ready()/onDeviceReady() of jquery-mobile/phonegap

本文关键字:onDeviceReady ready document phonegap jquery mobile      更新时间:2023-09-26

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

现在,当页面被加载时,我想加载一个script(.js file)。基本上是CCD_ 2或CCD_。如何做到这一点?

//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分析代码的一个稍微修改过的版本,用于向DOM异步添加脚本。

更新

您还可以将<script>标记的defer属性设置为true,并且在准备好DOM之后才会执行该属性。请参阅此处的一些文档:https://developer.mozilla.org/en-US/docs/HTML/Element/Script