一起使用 JQuery-Mobile/Phonegap 的正确方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10945643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:00:23  来源:igfitidea点击:

Correct way of using JQuery-Mobile/Phonegap together?

jqueryjquery-mobilecordova

提问by Juw

What is the correct way (to this date) to use JQuery Mobile and Phonegap together?

将 JQuery Mobile 和 Phonegap 一起使用的正确方法(到目前为止)是什么?

Both frameworks need to load before they can be used. How can I be sure that both are loaded before I can use them?

两个框架都需要加载才能使用。在我可以使用它们之前,如何确保它们都已加载?

回答by Octavian

You can use deferred feature of JQuery.

您可以使用 JQuery 的延迟功能。

var deviceReadyDeferred = $.Deferred();
var jqmReadyDeferred = $.Deferred();

document.addEventListener("deviceReady", deviceReady, false);

function deviceReady() {
  deviceReadyDeferred.resolve();
}

$(document).one("mobileinit", function () {
  jqmReadyDeferred.resolve();
});

$.when(deviceReadyDeferred, jqmReadyDeferred).then(doWhenBothFrameworksLoaded);

function doWhenBothFrameworksLoaded() {
  // TBD
}

回答by Cristian Romanescu

Here's how it worked for me, based on the example above

根据上面的示例,这是对我有用的方法

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
        <title>InforMEA</title>
    </head>
    <body>
        <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
        <script type="text/javascript">
            var dd = $.Deferred();
            var jqd = $.Deferred();
            $.when(dd, jqd).done(doInit);

            $(document).bind('mobileinit', function () {
                jqd.resolve();
            });
        </script>
        <script type="text/javascript" src="js/jquery.mobile-1.2.0.js"></script>
        <script type="text/javascript" src="cordova-2.2.0.js"></script>
        <script type="text/javascript">
            document.addEventListener('deviceready', deviceReady, false);
            function deviceReady() {
                dd.resolve();
            }

            function doInit() {
                alert('Ready');
            }
        </script>
    </body>
</html>

回答by Coder_sLaY

In order to use phonegap along with jquery mobile, you need to use it like this

为了将 phonegap 与 jquery mobile 一起使用,您需要像这样使用它

<head>
<title>Index Page</title>

<!-- Adding viewport -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, user-scalable=no">

<!-- Adding jQuery scripts -->
<script type="text/javascript" src="jquery/jquery-1.7.1.min.js"></script>

<!-- Since jQuery Mobile relies on jQuery core's $.ajax() functionality,
 $.support.cors & $.mobile.allowCrossDomainPages must be set to true to tell
 $.ajax to load cross-domain pages. -->
<script type="text/javascript">
    $(document).bind("mobileinit", function() {
        $.support.cors = true;
        $.mobile.allowCrossDomainPages = true;
    });
</script>

<!-- Adding Phonegap scripts -->
<script type="text/javascript" charset="utf-8"
    src="cordova/cordova-1.8.0.js"></script>

<!-- Adding jQuery mobile scripts & CSS -->
<link rel="stylesheet" href="jquerymobile/jquery.mobile-1.1.0.min.css" />
<script type="text/javascript"
    src="jquerymobile/jquery.mobile-1.1.0.min.js"></script>

</head>
<script type="text/javascript">
    // Listener that will invoke the onDeviceReady() function as soon as phonegap has loaded properly
    document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
        navigator.splashscreen.hide();

        document.addEventListener("backbutton", onBackClickEvent, false); // Adding the back button listener    

    }
    </script>
<body>
<div data-role="page" id="something" data-ajax="false">
        <script type="text/javascript">
            $("#something").on("pageinit", function(e) {

            });

            $("#something").on("pageshow", function(e) {

            });

            $("#something").on("pagebeforeshow", function(e) {

            });
        </script>

        <div data-role="header">            
        </div>

        <div data-role="content">           
        </div>      
    </div>
</body>  

回答by Jeffrey Van Alstine

As many people suggested using a deferred is an okay option as long as you don't care what order devicereadyand mobileinithappe in. But in my case, I needed a few pageshowevents when the application first loaded and mobileinitand by extension those pageshow/pagebeforeshow/etc events were all firing before devicereadyfinished, so I couldn't bind to them properly using a deferred on them. This race condition was not a good thing.

很多人建议使用延迟是一个不错的选择,只要你不关心什么顺序devicereadymobileinit事件。但就我而言,pageshow当应用程序第一次加载时我需要一些事件,mobileinit并且扩展那些pageshow/ pagebeforeshow/etc 事件是所有在deviceready完成之前触发,所以我无法使用延迟正确绑定到它们。这种比赛条件不是一件好事。

What I needed to do was make sure 'mobileinit' didn't take place until after 'deviceready' was already fired. Because mobileinitfires immediately when you load JQM I chose to use jQuery.getScriptto load it AFTER devicereadywas already finished.

我需要做的是确保 'mobileinit' 直到 ' deviceready' 已经被解雇后才发生。因为mobileinit在加载 JQM 时会立即触发,所以我选择在已经完成jQuery.getScript后使用它来加载它deviceready

<script src="cordova-2.2.0.js"></script>
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/async.min.js"></script>
<script src="js/app.js"></script>
<script>
  document.addEventListener(
    'deviceready',
    function () {
      $('body').css('visibility', 'hidden');
      $(document).one("mobileinit", function () {
        app.init();
        $('body').css('visibility', '');
      });
      $.getScript('js/jquery.mobile-1.2.0.min.js');
    },
    false
  );
</script>

The reason I'm hiding the body is that a side effect of this method is a half second of visibility of the original HTML document before jquery.mobile loads. In this case hiding it an extra half second of empty space is preferred to seeing the unstyled document.

我隐藏正文的原因是这种方法的副作用是在 jquery.mobile 加载之前原始 HTML 文档的可见性有半秒。在这种情况下,将其隐藏半秒的空白空间比查看无样式文档更可取。

回答by Allie Hoch Janoch

I believe that it isn't necessary to use the deferred feature. (Maybe this isn't necessary with newer versions of phonegap?) I have this in the head of my index.html file and everything works fine. I do think that the order of including jquery, phonegap and jquery mobile are important.

我认为没有必要使用延迟功能。(也许这对于较新版本的 phonegap 来说不是必需的?)我在 index.html 文件的头部有这个,一切正常。我确实认为包含 jquery、phonegap 和 jquery mobile 的顺序很重要。

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />

    <!-- Adding jQuery -->
    <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>

    <!-- Add Phonegap scripts -->
    <script type="text/javascript" src="phonegap.js"></script>

    <!-- Add jQuery mobile -->
    <link rel="stylesheet" href="css/jquery.mobile-1.3.2.css" />
    <script type="text/javascript" src="js/jquery.mobile-1.3.2.min.js"></script>

    <title>MY TITLE</title>
</head>

回答by Ztuons Ch

this is work for me. base on dhaval,this sample when I learn using sqlite

这对我来说是工作。基于 dhaval,当我学习使用 sqlite 时的这个示例

<!DOCTYPE html>
<html>
 <head>
<title>Cordova Sqlite+Jquery</title>
<script type="text/javascript" charset="utf-8" src="js/jquery-1.8.3.min.js"></script>   
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script type="text/javascript" charset="utf-8">`

// Call onDeviceReady when Cordova is loaded.
//
// At this point, the document has loaded but cordova-1.8.0.js has not.
// When Cordova is loaded and talking with the native device,
// it will call the event `deviceready`.
//
function onLoad() {
    document.addEventListener("deviceready", onDeviceReady, false);
}

// Populate the database 
//
function populateDB(tx) {
    tx.executeSql('DROP TABLE IF EXISTS DEMO');
    tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
    tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
    tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}

// Query the database
//
function queryDB(tx) {
    tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
}

// Query the success callback
//
function querySuccess(tx, results) {
    var len = results.rows.length;
    //console.log("DEMO table: " + len + " rows found.");
    $('#result').html("DEMO table: " + len + " rows found.");
    var listval = '';
    for (var i=0; i<len; i++){
        //console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data =  " + results.rows.item(i).data);
         listval += '<li>'+ results.rows.item(i).data + '[' + results.rows.item(i).id + '] </li>';
    }

    $('#listItem').html(listval);

}

// Transaction error callback
//
function errorCB(err) {
    console.log("Error processing SQL: "+err.code);
}

// Transaction success callback
//
function successCB() {
    var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
    db.transaction(queryDB, errorCB);
}

// Cordova is loaded and it is now safe to make calls Cordova methods
//
function onDeviceReady() {
    // Now safe to use the Cordova API
    //alert('ready');
    var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
    db.transaction(populateDB, errorCB, successCB);
    //$('#result').html('hello');
}

</script>
  </head>
 <body onload="onLoad()">
  <div>result:</div><div id="result"></div>
  <ul id="listItem">
  </ul>
 </body>
 </html>

回答by Erik

To build on @Jeffrey's answer, I found a much cleaner way which hides the HTML markup until JQM has finished processing the page and renders the first Page element, since I've noticed that 1/2 second flicker of bare markup before JQM renders.

为了建立在@Jeffrey 的回答之上,我找到了一种更简洁的方法,它隐藏 HTML 标记,直到 JQM 完成页面处理并呈现第一个 Page 元素,因为我注意到在 JQM 呈现之前 1/2 秒的裸标记闪烁。

You only need to hide all the markup with css...PageShow() by JQM will toggle the visibility for you.

您只需要使用 css...PageShow() 隐藏所有标记,JQM 将为您切换可见性。

//snip
<style type="text/css">
.hide {
  display:none;
}
</style>

//snip - now the markup notice the hide class
<div id="page1" data-role="page" class="hide">
     //all your regular JQM / html form markup
</div>

//snip -- down to the end of /body
<script src="cordova-2.2.0.js"></script>
<script src="js/jquery-1.8.2.min.js"></script>
<script>
   document.addEventListener(
     'deviceready',
      function () {
         $(document).one("mobileinit", function () {
         //any JQM init methods

       });
      $.getScript('js/jquery.mobile-1.2.0.min.js');
   },
   false);
</script>

回答by Jens Peters

The following worked for me on PG 2.3 and JQM 1.2, incl. Facebook Connect Plugin:

以下内容在 PG 2.3 和 JQM 1.2 上对我有用,包括。Facebook 连接插件:

<head>
<script src="./js/jquery-1.8.2.min.js"></script>
<script>
    $.ajaxSetup({
        dataType : 'html'
    });

    var dd = $.Deferred();
    var jqd = $.Deferred();
    $.when(dd, jqd).done(function() {                

        FB.init({ appId: auth.fbId, nativeInterface: CDV.FB, useCachedDialogs: false });
    });

    $(document).bind('mobileinit', function () {
        jqd.resolve();
    });                        
</script>
<script src="./js/jquery.mobile-1.2.0.min.js"></script>
<script>
    $.mobile.loader.prototype.options.text = "loading";
    $.mobile.loader.prototype.options.textVisible = true;
    $.mobile.loader.prototype.options.theme = "a";
    $.mobile.loader.prototype.options.html = "";

    $.mobile.ajaxEnabled = false;
    $.mobile.allowCrossDomainPages = true;
    $.support.cors = true;       

    $('[data-role=page]').live('pagecreate', function(event) {                      
        tpl.renderReplace('login', {}, '#content-inner', function() {                   
            auth.init();
        });
    });
</script>
<script src="./js/cordova-2.3.0.js"></script>
<script src="./js/cdv-plugin-fb-connect.js"></script>
<script src="./js/facebook_js_sdk.js"></script>                     
<!--some more scripts -->
<script>        
    document.addEventListener('deviceready', function() {
        dd.resolve();
    }, false);                        
</script>  
<head>

回答by dhaval

Loading of PhoneGap is slightly different than loading of jQuery. jQuery works more as a utility library so you include that and it is available for use immediately. On the other hand PhoneGap requires support from native code for proper initialization so it is not ready to use soon after included in the page.

PhoneGap 的加载与 jQuery 的加载略有不同。jQuery 更像是一个实用程序库,因此您可以将其包含在内,并且可以立即使用。另一方面,PhoneGap 需要本机代码的支持才能进行正确的初始化,因此在包含在页面中后不能很快使用。

Phonegap suggests to register and wait for devicereadyevent executing any native specific code.

Phonegap 建议注册并等待deviceready执行任何本机特定代码的事件。

<!DOCTYPE html>
<html>
  <head>
    <title>PhoneGap Example</title>

    <script type="text/javascript" charset="utf-8" src="lib/jquery.min.js"></script>
    <script type="text/javascript">
        // jquery code here
    </script>
    <script type="text/javascript" charset="utf-8" src="lib/android/cordova-1.7.0.js"></script>
    <script type="text/javascript" charset="utf-8">

    function onLoad(){
        document.addEventListener("deviceready", onDeviceReady, false);
    }

    // Cordova is ready
    function onDeviceReady() {
        // write code related to phonegap here
    }
    </script>
  </head>
  <body onload="onLoad()">
    <h1>Phonegap Example</h1>
  </body>
</html>

For more info check doc

有关更多信息,请查看文档