Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I wait for both Cordova and jQuery to load their libraries?

jQuery has the "ready" function:

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

and the cordova documentation says to add an event listener:

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

Do I need to call both of these to make sure both the libraries are loaded before any code that references them is used?

Does it make sense to nest them, i.e.:

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

Just trying to figure out the best way to do this, maybe I am overthinking it

like image 837
kburbach Avatar asked Mar 22 '23 01:03

kburbach


1 Answers

JS files are loaded sequentially. So in your HTML just put your .js file after jQuery and cordova and it won't run before both are loaded.

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

As for ready events, if you don't want to nest them, you could construct your own event for when all the libraries are ready:

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
}

This will work, and go() will fire when all are loaded, however I'm really not sure if you actually need all of this and is there a simper way to do it.

like image 161
tomca32 Avatar answered Apr 06 '23 15:04

tomca32