2012-02-27 64 views
20

我正在开发一个使用PhoneGap和jQuery Mobile的应用程序。我想要加载一个script(.js file)。基本上onDeviceReady$(document).ready()。怎么做?

回答

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

这第二代码片段是谷歌分析代码稍加修改的版本,用于将脚本添加到DOM异步。

UPDATE

您还可以设置一个<script>标签truedefer属性,它不会在DOM已经准备后,直到被执行。看到这里的一些文档:https://developer.mozilla.org/en-US/docs/HTML/Element/Script

+2

谢谢Jasper.Answer是精确的...:D – 2012-02-27 06:57:10

+0

我也遇到了问题,其中IE8刷新。使用$(document).ready()调用是为我修复的。 Thx的答案! – PhilNicholas 2014-01-13 05:57:13

+1

注意:getScript是异步的,因此调用在被调用脚本中声明的函数可能会导致“未定义”错误。请参阅:http://stackoverflow.com/questions/1130921/is-the-callback-on-jquerys-getscript-unreliable-or-am-i-doing-something-wrong – Costa 2015-04-02 05:35:56

相关问题