Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  149] [ 1]  / answers: 1 / hits: 42501  / 13 Years ago, mon, february 27, 2012, 12:00:00

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?


More From » jquery

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


[#87192] Saturday, February 25, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ignacio

Total Points: 467
Total Questions: 128
Total Answers: 79

Location: Luxembourg
Member since Tue, Mar 14, 2023
1 Year ago
ignacio questions
;