I am developing an application using PhoneGap and jQuery Mobile.
Now when the page gets loaded then I want to load a script(.js file)
. Basically onDeviceReady
or $(document).ready()
. How to do that?
//wait for document.ready to fire
$(function () {
//then load the JavaScript file
$.getScript('script.js');
});
http://api.jquery.com/jquery.getscript
//create a callback function
function myCallback () {
//create a script element and set it's type and async attributes
var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true;
//set the source of the script element
script.src = 'script.js';
//add the script element to the DOM
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(script, s);
}
//add event listener for the deviceready function to run our callback function
document.addEventListener("deviceready", myCallback, false);
http://docs.phonegap.com/en/1.4.1/phonegap_events_events.md.html#deviceready
This second code snippet is a slightly modified version of the Google Analytic code, used to add a script to the DOM asynchronously.
UPDATE
You can also set the defer
attribute of a <script>
tag to true
and it won't be executed until after the DOM has been prepared. See some documentation here: https://developer.mozilla.org/en-US/docs/HTML/Element/Script
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With