67

jqueryでphonegapアプリを作っています。コード全体を JQuery の$(document).ready()ようなものにラップする必要があるかどうか混乱しています

$(document).ready(function(){
    //mycode
});

または phonegap の deviceready イベント内

document.addEventListener("deviceready", function(){
    //mycode
});

現在使用してdocument.readyいますが、 内のいくつかの Phonegap API メソッドにアクセスしようとすると、問題が発生する可能性があると思いますdocument.ready

私のコードをラップするのに最適なイベントは、document.ready と deviceready のどちらですか?

4

6 に答える 6

88

A key point in the answer is this line from the documentation of the deviceready event.

This event behaves differently from others in that any event handler registered after the event has been fired will have its callback function called immediately.

What this means is that you won't 'miss' the event if you add a listener after the event has been fired.

So, first move all the initialization code to the onDeviceReady function. Then first handle the document.ready. Within the document.ready if you determine that you are running in a browser, just call the onDeviceReady function, otherwise add the deviceready listener. This way when you are in the onDeviceReady function you are sure that all the needed 'ready's have happened.

$(document).ready(function() {
    // are we running in native app or in a browser?
    window.isphone = false;
    if(document.URL.indexOf("http://") === -1 
        && document.URL.indexOf("https://") === -1) {
        window.isphone = true;
    }

    if( window.isphone ) {
        document.addEventListener("deviceready", onDeviceReady, false);
    } else {
        onDeviceReady();
    }
});

function onDeviceReady() {
    // do everything here.
}

The isphone check works because in phonegap, the index.html is loaded using a file:/// url.

于 2013-01-01T08:29:04.953 に答える
28

おかしなことが起こらないようにするには、deviceready イベントを使用する必要があります。

ドキュメントの状態:

これは、すべての PhoneGap アプリケーションが使用する必要がある非常に重要なイベントです。

PhoneGap は、ネイティブと JavaScript の 2 つのコード ベースで構成されています。ネイティブ コードの読み込み中は、カスタムの読み込みイメージが表示されます。ただし、JavaScript は DOM がロードされた後にのみロードされます。これは、Web アプリケーションがロードされる前に PhoneGap JavaScript 関数を呼び出す可能性があることを意味します。

PhoneGap が完全に読み込まれると、PhoneGap の deviceready イベントが発生します。デバイスが起動したら、PhoneGap 関数を安全に呼び出すことができます。

document.addEventListener通常、 HTML ドキュメントの DOM がロードされたら、イベント リスナーをアタッチします。

こちらのドキュメントをお読みください: http://docs.phonegap.com/en/1.0.0/phonegap_events_events.md.html

于 2012-09-25T04:11:06.553 に答える
0

私は PhoneGap Build cli-6.2.0 を使用しています。あなたが提案した手順をテストすると、 function 内で何もしませんonDeviceReady()

古いバージョンの PGB でも動作します。

	$(document).ready(function() { 
		window.isphone = false;
		if (document.URL.indexOf("http://") === -1 && document.URL.indexOf("https://") === -1) { window.isphone = true }
		if (window.isphone) { document.addEventListener("deviceready", this.onDeviceReady, false); } else { onDeviceReady(); }
	});
	function onDeviceReady() {
		alert( window.isphone ); 		
	}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

于 2016-09-05T14:29:13.110 に答える