22

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?

Jasper
  • 75,717
  • 14
  • 151
  • 146
coderslay
  • 13,960
  • 31
  • 73
  • 121

1 Answers1

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

Jasper
  • 75,717
  • 14
  • 151
  • 146
  • 2
    Thanks Jasper.Answer is Precise...:D – coderslay Feb 27 '12 at 06:57
  • I, too, was experiencing the problem where IE8 was breaking on refresh. Using the $(document).ready() call is what fixed it for me. Thx for the answer! – Phil Nicholas Jan 13 '14 at 05:57
  • 1
    NB: getScript is asynchronous so calling a function declared within the called script may result in "undefined" errors. See: http://stackoverflow.com/questions/1130921/is-the-callback-on-jquerys-getscript-unreliable-or-am-i-doing-something-wrong – Costa Apr 02 '15 at 05:35
  • @Costa The `$.getScript` method also has a callback parameter you can use. – Jasper Apr 02 '15 at 17:21
  • @Jasper the callback runs when the code is **loaded**, not when the code is **executed**, so it's not reliable – Costa Apr 03 '15 at 05:09