2016-04-14 127 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(); 
 
    });