-->

deviceready not firing in cordova

2020-08-18 07:06发布

问题:

The deviceready isn't firing correctly (at least in iOS) for my cordova project. I have searched for hours and still cannot figure this out. Am I doing something incorrectly? The path to js/cordova.js exists as well:

<html>
<head>
    <title>Geolocation</title>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, target-densityDpi=device-dpi, user-scalable=no" />
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/app.css">
    <script type="text/javascript">

    // Fastclick
    if ('addEventListener' in document) {
        document.addEventListener('DOMContentLoaded', function() {
        FastClick.attach(document.body);
        }, false);
    }

    </script>
    <script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

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

    // device APIs are available
    //
    function onDeviceReady() {
        alert("ready");
        // Now safe to use device APIs
    }

    </script>
</head>
<body onload="onLoad()">

I'm not sure what I'm missing as I'm not getting any errors if I inspect in Chrome

回答1:

There's no need to have the cordova.js inside your www/js/ folder because that file is copied from another location to platforms/ios/platform_www (i.e. by running: cordova build ios) at the same level that the index.html file, so in order to have a proper configuration, the next statement:

<script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>

must be changed to:

<script type="text/javascript" charset="utf-8" src="cordova.js"></script>


回答2:

deviceready event is essential to any application. It signals that Cordova's device APIs have loaded and are ready to access.

Update

So I got "deviceready" to work by removing the onload="onLoad()" from the body and replacing this:

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

with just this:

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


回答3:

I had this same issue, but in my case cordova.js was already properly included.

Eventually what worked for me was a simple remove and add of the ios platform:

cordova platform remove ios
cordova platform add ios

It had been quite a while since I had completely re-built the ios platform and other major changes had taken place during that time (Cordova upgrade, XCode upgrade, etc). It's possible that my config.xml or existing ios build was somehow incompliant with the latest Cordova requirements.



回答4:

I had the same problem, my solution was to add :

<script type="text/javascript" src="cordova.js"></script>

in the HTML file and everything worked perfectly