需要deviceready里面的文件准备好了吗?

Need the document ready inside deviceready?

在 phonegap 中,我需要在 deviceready 事件函数中使用 $(document).ready(...) 吗?我可以确定调用 deviceready 事件时已加载文档吗?

示例:

document.addEventListener('deviceready', 
   function() {
            $(document).ready(function() { // is this too much? 
                initCampusWeb(); 
            });
        }, false);

根据 cordova 文档:

Cordova consists of two code bases: native and JavaScript. While the native code loads, a custom loading image displays. However, JavaScript only loads once the DOM loads. This means the web app may potentially call a Cordova JavaScript function before the corresponding native code becomes available.

The deviceready event fires once Cordova has fully loaded. Once the event fires, you can safely make calls to Cordova APIs. Applications typically attach an event listener with document.addEventListener once the HTML document's DOM has loaded.

The deviceready event behaves somewhat differently from others. Any event handler registered after the deviceready event fires has its callback function called immediately.

只有在页面文档对象模型 (DOM) 准备好执行 JavaScript 代码后,$(document).on("ready") 才会 运行。

你只能使用 document.addEventListener('deviceready') 用于那个 prupouse

这是正确的方法:

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {

   // Your code here

}

它的工作方式是先 jQuery(document).ready() 触发然后 deviceready 触发。

我通常这样设置我的代码:

jQuery(document).ready(function () {
    // do document ready stuff
}).on('deviceready', function () {
    // do deviceready stuff, put all calls to plugins in here
});

所以关于 initCampusWeb 去向的问题取决于您在该函数中所做的事情。如果它使用插件,将它放在 deviceready 处理程序中。

我不确定 deviceready 总是会在文档准备好后触发,所以我采用了以下异步方法,如下所示:

bindEvents: function () {
    var me = this;

    document.addEventListener('deviceready', function () {
        me.onDeviceReady();
    }, false);

    $(document).ready(function () {
        me.onDocumentReady();
    });
},

documentReady: false,
onDocumentReady: function () {
    this.documentReady = true;
    this.checkReady();
},

deviceReady: false,
onDeviceReady: function () {
    this.deviceReady = true;
    this.checkReady();
},

checkReady: function (id) {
    if (this.documentReady && this.deviceReady) this.load();
},

load: function () {
    // do stuff
}

这样您就不会在事件发生后冒险附加处理程序。可能有点矫枉过正,但给了我完全的信心和异步可扩展性(以防我希望 load() 等待另一个事件完成)。