2016-04-14 125 views
-2

我想加载谷歌地图JS按钮单击(而不是包括在头优化)。确保执行顺序︰javascript

 $.when(
      $.getScript("https://maps.googleapis.com/maps/api/js?v=3.17&libraries=places") 
       .done(function() { 
       console.log('loaded'); 
       }) 
     ) 
     .then(_getCurrentLocation()) 
     .then(_lookForLatLang()) 

getCurrentLocation不过是浏览器支持的地理定位对象,它基于反向查找完成。

我想严格按照Javascript文件的执行顺序,但它不是理想的情况。我可以看到getCurrentLocation FIRST &的输出,然后getScript日志。

这个脚本怎么了?

+0

'getScript'返回一个承诺。你不需要'$ .when'。 – SLaks

+0

检查您的控制台是否有错误(按F12)。我相信你会看到一些有助于解释为什么它不起作用的东西。 –

回答

2

使用回调:

$.getScript("https://maps.googleapis.com/maps/api/js?v=3.17&libraries=places") 
 
    .done(function() { 
 
     console.log('loaded'); 
 
    }, function() { 
 
     (_getCurrentLocation()); 
 
     (_lookForLatLang()); 
 
    });

+0

为什么你的函数调用需要额外的参数? '(_getCurrentLocation())'可以只是'_getCurrentLocation()'。 – jfriend00

3
.then(_getCurrentLocation()) 

你刚才叫_getCurrentLocation立即并通过返回值来then()(就像任何其他函数调用)。

你想传递函数本身。

+0

为什么不显示正确的代码而不是只突出显示错误的代码? – jfriend00

+0

@ jfriend00:因为我想让老师们明白,不要从StackOverflow中复制代码的答案。 – SLaks

+0

对不起,但我不买它。我认为其他答案显示正确的代码是更好的答案。解释这个问题的文本,所以OP希望理解也使得答案成为更好的答案,但不以牺牲实际上没有显示正确的解决方案为代价。 – jfriend00

1

$.getScript("https://maps.googleapis.com/maps/api/js?v=3.17&libraries=places") 
 
    .done(function() { 
 
    console.log('loaded'); 
 
    _getCurrentLocation(); 
 
    _lookForLatLang(); 
 
    });