4

jQuery 具有“就绪”功能:

$(function() {...});

并且cordova文档说要添加一个事件监听器:

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

我是否需要调用这两个库以确保在使用任何引用它们的代码之前加载这两个库?

嵌套它们是否有意义,即:

$(function(){
    onDeviceReady(){...}
}

只是想找出最好的方法来做到这一点,也许我想多了

4

3 回答 3

7

JS 文件是按顺序加载的。因此,在您的 HTML 中,只需将 .js 文件放在 jQuery 和 cordova 之后,它就不会在两者都加载之前运行。

<script src="jQuery"></script>
<script src="cordova"></script>
<script src="yourScript"></script> <!-- this won't run before both jQ and cordova are loaded -->

至于准备好的事件,如果您不想嵌套它们,您可以在所有库准备好时构建自己的事件:

var listener = {
    jquery: false,
    cordova: false,
    fire: function(e) {listener[e] = true; if (listener.jquery && listener.cordova) go();
};
document.addEventListener("deviceready", function(){listener.fire('cordova'), false();
$(document).ready(function(listener.fire('jquery')){});

function go() {
// your code here
}

这将起作用,并且 go() 将在所有内容加载后触发,但是我真的不确定您是否真的需要所有这些,并且有更简单的方法来做到这一点。

于 2013-10-14T17:33:15.773 回答
0

将 document.ready 放入 deviceready:

var onDeviceReady = function (){
    jQuery(document).ready(function (){
        // go!
    });
};

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

jQuery 的ready()DOMContentLoaded的代理,表示文档已被解析并且可以安全地被查询或操作。

jQuery 本身 ( jQuery, $) 在库执行完毕后立即可用;你不需要做任何特别的事情来等待。

于 2013-10-14T18:52:01.700 回答
0

你可以在 deviceready 之后调用你的 jquery 函数。让我给你一个完整的例子来说明如何做到这一点。首先确保你已经添加了你要使用的所需的cordova/phonegap插件。在我的例子中,我已经加载了设备插件。

打开一个空白文档,添加 html 骨架,然后在 html 的头部,添加以下内容:

<script type="text/javascript" charset="utf-8" src="cordova.js"></script>//include the cordova.js file
<script type="text/javascript" charset="utf-8" src="js/jquery.min.js"></script>//include the jquery.min.js file strictly after the cordova.js file
<script type="text/javascript" charset="utf-8">


    // Wait for device API libraries to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // device APIs are available
    //
    function onDeviceReady() {

        $(document).ready(function(){ //jquery starts here and is inside the device ready function


            //the next few lines are now the calling my plugins
            //#deviceproperties is a paragraph in html that has an id deviceproperties
            //#hideme is a span inside the paragaraph that has the id deviceproperties.inside the span is the statement that is saying 'loading device properties' and will be removed as soon as the script hide() runs

           $('#deviceProperties').prepend("<br>" + device.cordova 
                                 + "<br>" + device.platform
                                 + "<br>" + device.uuid
                                 + "<br>" + device.version
                                  );

            $('#hideme').hide();//hide the loading device properties
        });//lets end jquery`s document.ready

    }//lets end cordova`s device ready

</script>

正在加载设备属性...

于 2017-05-15T10:58:32.527 回答