Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a script on $(document).ready()/onDeviceReady() of jquery-mobile/phonegap [duplicate]

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?

like image 874
coderslay Avatar asked Feb 27 '12 06:02

coderslay


1 Answers

//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

like image 157
Jasper Avatar answered Nov 06 '22 02:11

Jasper