如何使用异步Javascript

How to use asynchronous Javascript?

本文关键字:Javascript 异步 何使用      更新时间:2024-04-26

我正在使用谷歌地图在移动应用程序中获取地址。当有互联网连接时,代码运行良好。如果没有,那么我的应用程序需要1分钟才能加载,或者有时会显示应用程序错误。这是由于在脚本中加载了一个URL,所以我想异步加载我的脚本。有人能给我一些逻辑来解决我的问题吗?我如何异步重写下面的脚本?

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true">
function address()
{
              var geocoder ;
              geocoder = new google.maps.Geocoder();
              var latlng = new google.maps.LatLng(latitude, longitude);
              geocoder.geocode({'latLng': latlng}, function(results, status) 
                {                   
                if (status == google.maps.GeocoderStatus.OK)
                 {
                        if (results[0])
                        {
                           var add= results[0].formatted_address ;
                           document.getElementById("location").innerHTML="Location : " + add ;
                        }
                        else 
                        {
                           document.getElementById("location").innerHTML="No Results found " ;
                        }
                }
                 else
                {
                //document.getElementById("location").innerHTML="Geocoder failed due to: " + status;
                //alert("Geocoder failed due to: " + status);               
                }
                });
}

这应该做到:

jQuery.getScript('https://maps.googleapis.com/maps/api/js?sensor=true', address);

getScript()jQuery.ajax()的辅助函数。如果你使用后者,你可以获得更多的控制和设置更多的选项,特别是timeout参数,这样它就不会永远旋转,或者cache参数,这样你就不必一直查找

类似的小提琴。抱歉fiddles不能直接使用外部资源,所以我必须创建一个更简单的脚本请求,但你可以看到回调引用了新的javascript。