开发加载谷歌地图的phonegap应用程序。使用以下两个 javascript 进行谷歌地图。一种 JavaScript 是从本地加载的,而其他 JavaScript 是从服务器加载的。
var script = document.createElement('script');
script.src = 'http://maps.google.com/maps/api/js?sensor=true';
script.type = 'text/javascript';
document.head.appendChild(script);
script.onload = function () {
var script1 = document.createElement('script');
script1.src = 'js/jquery.ui.map.js';
script1.type = 'text/javascript';
document.head.appendChild(script1);
script1.onload = function () {
alert(google.maps.LatLng);
}
};
两个 javascript 都应该在 html 页面加载后加载。尝试了下面的代码并引用了各种博客,但它不起作用。
如果在 html 页面的 header 标签中编写相同的脚本,那么它可以正常工作。但在我的应用程序中,我需要动态加载它。
请帮忙......
已解决:
var doc_write = document.write; // Remember original method;
document.write = function(s) {$(s).appendTo('body')};
$.getScript('<a href="http://maps.google.com/maps/api/js?sensor=true" rel="noreferrer noopener nofollow">http://maps.google.com/maps/api/js?sensor=true</a>').done(function()
{
$.getScript('js/jquery.ui.map.js').done(function()
{
document.write = doc_write; // Restore method
setTimeout(function()
{
alert(google.maps.LatLng);
},1000);
})
.fail(function(jqxhr, settings, exception)
{
alert(exception); // this gets shown
document.write = doc_write; // Restore method
});
}).fail(function()
{
alert('failed to load google maps');
});
问题: 初始化需要一些时间。
最佳答案
在设备准备就绪后调用您的 JavaScript 函数。因为如果您通过 Xcode 使用手机间隙,设备准备功能需要一些时间来加载,并且您的脚本会在它之前调用。
关于javascript - phonegap - 动态添加 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22498802/