如何在$(document).ready()/ onDeviceReady()上加载脚本jquery-mobile / phonegap [英] How to load a script on $(document).ready()/onDeviceReady() of jquery-mobile/phonegap
问题描述
我正在使用PhoneGap和jQuery Mobile开发应用程序。
现在当页面加载时,我想加载一个脚本。 js文件)
。基本上 onDeviceReady
或 $(document).ready()
。如何做?
//等待document.ready启动
$(function(){
//然后加载JavaScript文件
$ .getScript('script.js');
});
http ://api.jquery.com/jquery.getscript
//创建回调函数
function myCallback(){
//创建一个脚本元素并设置它的类型和异步属性
var script = document.createElement('script'); script.type ='text / javascript'; script.async = true;
//设置脚本元素的源代码
script.src ='script.js';
//将脚本元素添加到DOM
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(script,s);
}
//为deviceready函数添加事件监听器以运行我们的回调函数
document.addEventListener(deviceready,myCallback,false);
http://docs.phonegap.com/en/1.4.1/phonegap_events_events.md.html#deviceready
此第二个代码段是Google分析代码的略微修改版本,用于异步向DOM添加脚本。
UPDATE / p>
您还可以设置< script> $ c>的
defer
属性$ c>标记为 true
,它将不会被执行,直到DOM准备好。请参阅这里的一些文档: https://developer.mozilla.org/en-US/docs/HTML / Element / Script
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?
//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
这篇关于如何在$(document).ready()/ onDeviceReady()上加载脚本jquery-mobile / phonegap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!