2012-02-27 77 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

相關問題